Jump to content

allow certain characters


aebstract

Recommended Posts

How can I check a string to see if it only contains certain characters, and if it contains anything else then it will let me know.

 

Say I have $string and I wanna make sure it only contains a,b,c,d,e,f,0,1,2,3,4,5,6,7,8, or 9 and if it contains anything else then it will return an error?

Link to comment
https://forums.phpfreaks.com/topic/98903-allow-certain-characters/
Share on other sites

Several ways... Regex:

 

<?php
$safelist = 'abcdef0123456789'; // any metacharacters in here (-, [, ], ect) must be escaped with \
$regex = '/[^'.$safelist.']/i';

if (preg_match($regex, $subject) )
   return FALSE; // found a bad character
?>

 

You could also explode your subject into an array of characters and use in_array, but I think this would be much slower.

 

You could also use strpos, and use an array of the disallowed character as $needle... but once again, I think this would be slower

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.