Jump to content

How can I not allow certain characters?


membot

Recommended Posts

str_replace() won't suffice if you want to strip out many different 'types' of characters.

 

You can use preg_replace for that but you need to learn some basic regex. Here is what you are looking for:

 

http://www.phpro.org/tutorials/Validating-User-Input.html

 

this will strip out: (a,b,c,d,e):

 

$str = 'abq dadewcdefgh';

echo preg_replace("/[abcde]/", "", $str);

Link to comment
Share on other sites

For the example you provided, str_replace() would be fine. There's no reason to use a regex when a string function will do the job.

 

Didn't realize - so do you mean use a series of str_replace to strip out each character? When would that become inefficient? How many characters say on a sample str size of 1000 characters?

 

Seems I need to delve more into the performance hit.

Link to comment
Share on other sites

Not quite sure what you mean by 'use a series of str_replace', but this will perform the same task as the preg_replace above. Performance-wise, based on the average of 100,000 iterations, they're nearly identical.

$str = 'abq dadewcdefgh';
$repl = range( 'a', 'e');
echo str_replace($repl, '', $str);

Link to comment
Share on other sites

Not quite sure what you mean by 'use a series of str_replace', but this will perform the same task as the preg_replace above. Performance-wise, based on the average of 100,000 iterations, they're nearly identical.

$str = 'abq dadewcdefgh';
$repl = range( 'a', 'e');
echo str_replace($repl, '', $str);

 

Ahh, I see. Thanks! Very helpful.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.