简体   繁体   中英

RegEx that works in Javascript won't do so in PHP

I will try to make my question short yet understandable, I have a simple RegEx I use in javascript to check for characters that aren't alphanumeric (AKA Symbols). It would be "/[$-/:-?{-~!"^_`[]]/"

In javascript, doing

if(/[$-/:-?{-~!"^_`\[\]]/.test( string ))

just works, if any of those characters are in the string, it will give true, else, it will give false. I tried to do the same in PHP, the following way

if(preg_match('/[$-/:-?{-~!"^_`\[\]]/', $string ))

other regexes work when done this way, but this particular one simply will give false no matter what when ran in PHP.

Is there any reason to this? Am I doing something wrong? Does PHP comprehend regexes in a different way? What should I change to make it work?

Thanks for your time.

Since php uses PCRE, you will get a pattern error using delimiter / as seen here http://regex101.com/r/3ILGgE/1

So, it should be escaped correctly.

Using / as the delimiter, the string is

'/[$-\/:-?{-~!"^_`\[\]]/'  

Using ~ as the delimiter, the string is

'~[$-/:-?{-\~!"^_`\[\]]~'  

Also, be aware you have a couple of range's in the class $-/ and :-? and {-~
that will include the characters between the from/to range characters as well
and does not include the range character - itself as it is an operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM