Search code examples
phpstrpos

find exact word in a var string in PHP


i'm trying to find an exact word inside a string.

example:

$word = "Many Blocks";

if (strpos($word, "Block")){
  echo "You found 1 Block";
}

if (strpos($word, "Blocks")){
  echo "You found many Blocks";
}

The problem here is both if are true.. and i need to find only if is the same word..


Solution

  • As Jay Blanchard says you need to do it with regex in following way:--

    $word = "Many Blocks";
    if ( preg_match("~\bBlocks\b~",$word) )
      echo "matched";
    else
      echo "no match";