PHP - regular expression for string of special characters

Morning SO. I am trying to determine if a string contains a list of specific characters.

I know that I should use preg_match for this, but my knowledge of regular expression is woeful, and I could not get information from other posts around this site. Since most of them just want to limit the lines az, AZ and 0-9. But I want some special characters to be allowed, for example ! @ Β£ ! @ Β£ , while others are not on the next line.

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

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

I originally wrote a match in Javascript, which simply looped every letter in the string, and then quoted each character in a different string until I found a match. Looking back, I can’t believe that I even tried to use such an archaic method. With the advent of json (and rewriting the application!) I will switch the match to php to return the error message via json.

I was hoping the regex guru could help convert the specified string to a regular expression string, but any feedback would be appreciated!

+7
source share
4 answers

Regexp for the "forbidden character list" is optional.

You can look at strpbrk . He must do the necessary work.

Here is a usage example

 $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

+12
source
 return preg_match('/[#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/', $string); 
+5
source
 $pattern = preg_quote('#$%^&*()+=-[]\';,./{}|\":<>?~', '#'); var_dump(preg_match("#[{$pattern}]#", 'hello world')); // false var_dump(preg_match("#[{$pattern}]#", 'he||o wor|d')); // true var_dump(preg_match("#[{$pattern}]#", '$uper duper')); // true 

You can probably cache $pattern , depending on your implementation.

(Although you look beyond regular expressions, strpbrk , as mentioned here)

+3
source

I think that what you are looking for can be greatly simplified, including the characters you want to resolve like this:

 preg_match('/[^\ w!@ Β£]/', $string) 

Here is a brief description of what is happening:

  • [^] = not included
  • \ w = letters and numbers
  • ! @ Β£ = list of characters you would also like to allow
0
source

All Articles