简体   繁体   中英

Regex match with special character

I'm having the following reg-ex which is working fine for the normal string match against an array,

preg_grep( "/^". $name . "$/i", $values);

However its not working for the string which has special characters like "Entertainment (General)".

Find a related thread however its for java script and also it didn't help.

Use the preg_quote function to escape any special characters that might be in the string:

preg_grep( "/^". preg_quote($name, '/') . "$/i", $values);

From the documentation :

preg_quote() puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

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