php - preg_match: can't find substring which has trailing special characters -


i have function uses preg_match check if substring in string. today realize if substring has trailing special characters special regular expression characters (. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -) or @, preg_match can't find substring though there.

this works, returns "a match found."

$find = "website scripting"; $string =  "php website scripting language of choice.";  if (preg_match("/\b" . $find . "\b/i", $string)) {     echo "a match found."; } else {     echo "a match not found."; } 

but doesn't, returns "a match not found."

$find = "website scripting @"; $string =  "php website scripting @ language of choice.";  if (preg_match("/\b" . $find . "\b/i", $string)) {     echo "a match found."; } else {     echo "a match not found."; } 

i have tried preg_quote, doesn't help.

thank suggestions!

edit: word boundary required, that's why use \b. don't want find "phone" in "smartphone".

you can check if characters around search word not word characters look-arounds:

$find = "website scripting @"; $string =  "php website scripting @ language of choice.";  if (preg_match("/(?<!\\w)" . preg_quote($find, '/') . "(?!\\w)/i", $string)) {     echo "a match found."; } else {     echo "a match not found."; } 

see ideone demo

result: a match found.

note double slash used \w in (?<!\\w) , (?!\\w), have escape regex special characters in interpolated strings.

the preg_quote function necessary search word - see - can have special characters, , of them must escaped if intended matched literal characters.

update

there way build regex smartly placed word boundaries around keyword, performance worse compared approach above. here sample code:

$string =  "php website scripting @ language of choice.";  $find = "website scripting @"; $find = preg_quote($find); if (preg_match('/\w$/u', $find)) {   //  setting trailing word boundary     $find .= '\\b';  }  if (preg_match('/^\w/u', $find)) {   //  setting leading word boundary     $find = '\\b' . $find; }  if (preg_match("/" . $find . "/ui", $string)) {     echo "a match found."; } else {     echo "a match not found."; } 

see another ideone demo


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -