Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Regex for a string of special characters

Tags:

regex

php

Morning SO. I'm trying to determine whether or not a string contains a list of specific characters.

I know i should be using preg_match for this, but my regex knowledge is woeful and i have been unable to glean any information from other posts around this site. Since most of them just want to limit strings to a-z, A-Z and 0-9. But i do want some special characters to be allowed, for example: ! @ £ and others not in the below string.

Characters to be matched on: # $ % ^ & * ( ) + = - [ ] \ ' ; , . / { } | \ " : < > ? ~

private function containsIllegalChars($string)
{
    return preg_match([REGEX_STRING_HERE], $string);
}

I originally wrote the matching in Javascript, which just looped through each letter in the string and then looped through every character in another string until it found a match. Looking back, i can't believe i even attempted to use such an archaic method. With the advent of json (and a rewrite of the application!), i'm switching the match to php, to return an error message via json.

I was hoping a regex guru could assist with converting the above string to a regex string, but any feedback would be appreciated!

like image 326
Stann0rz Avatar asked Dec 20 '12 10:12

Stann0rz


1 Answers

Regexp for a "list of disallowed character" is not mandatory.

You may have a look at strpbrk. It should do the job you need.

Here's an example of usage

$tests = array(
    "Hello I should be allowed",
    "Aw! I'm not allowed",
    "Geez [another] one",
    "=)",
    "<WH4T4NXSS474K>"
);
$illegal = "#$%^&*()+=-[]';,./{}|:<>?~";

foreach ($tests as $test) {
    echo $test;
    echo ' => ';
    echo (false === strpbrk($test, $illegal)) ? 'Allowed' : "Disallowed";
    echo PHP_EOL;
}

http://codepad.org/yaJJsOpT

like image 123
Touki Avatar answered Nov 15 '22 13:11

Touki