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);

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.

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);

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.