aebstract Posted April 1, 2008 Share Posted April 1, 2008 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 More sharing options...
discomatt Posted April 1, 2008 Share Posted April 1, 2008 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 Link to comment https://forums.phpfreaks.com/topic/98903-allow-certain-characters/#findComment-506074 Share on other sites More sharing options...
discomatt Posted April 1, 2008 Share Posted April 1, 2008 As a second note, in the regex example, you can even use ranges to make things easier $safelist='a-f0-9'; or $safelist='a-f\d'; Link to comment https://forums.phpfreaks.com/topic/98903-allow-certain-characters/#findComment-506076 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.