Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find exact string inside a string

Tags:

string

php

I have two strings "Mures" and "Maramures". How can I build a search function that when someone searches for Mures it will return him only the posts that contain the "Mures" word and not the one that contain the "Maramures" word. I tried strstr until now but it does now work.

like image 218
Tudor Ravoiu Avatar asked Apr 29 '13 16:04

Tudor Ravoiu


3 Answers

You can do this with regex, and surrounding the word with \b word boundary

preg_match("~\bMures\b~",$string)

example:

$string = 'Maramures';
if ( preg_match("~\bMures\b~",$string) )
  echo "matched";
else
  echo "no match";
like image 181
Crayon Violent Avatar answered Sep 23 '22 14:09

Crayon Violent


Use preg_match function

if (preg_match("/\bMures\b/i", $string)) {
    echo "OK.";
} else {
    echo "KO.";
}
like image 37
Brucee Avatar answered Sep 19 '22 14:09

Brucee


How do you check the result of strstr? Try this here:

$string = 'Maramures';
$search = 'Mures';
$contains = strstr(strtolower($string), strtolower($search)) !== false;
like image 31
rekire Avatar answered Sep 22 '22 14:09

rekire