Search code examples
phptextwords

PHP Find all occurences of a whole word from a text


Here is my problem, I have a text in PHP :

$text = "Car is going with 10 meters/second"

$find = array("meters","meters/second");

now when I do this :

 foreach ($find as $f)
   {
     $count = substr_count($text,$f);
    } 

The output is :

meters -> 1
meters/second -> 1 

Normally I consider meters/second as a whole word, so meters shouldn't be counted, only meters/second since no space seperates them

Thus What I Expect :

meters -> 0
meters/second -> 1

Solution

  • You can do it with a regular expression, \b won't work because / is a word boundary, but something like that should work:

    preg_match_all(",meters([^/]|$),", $text, $matches);
    print_r($matches[0]);