Search code examples
phpstringstrpos

php find character in string but the character alone


I want to find 4 in a string. Just 4, not 44 or 14 or 4444 ...

I cannot use strpos because it returns 0 when 4 is found but also when 44 is found or when 444444 is found.

What function should I use?

Thanks


Solution

  • Use preg_match() with negative lookbehind and negative lookahead:

    preg_match('/((?<!4)4(?!4))/', $string, $m);
    if ($m && count($m) == 2) {
      // matched "only one 4"
    }