php 在字符串中查找字符但单独查找字符

php find character in string but the character alone

我想在一个字符串中找到 4。只是 4,不是 44 或 14 或 4444 ...

我不能使用 strpos,因为它 returns 0 当找到 4 时,当找到 44 或找到 444444 时也是。

我应该使用什么功能?

谢谢

使用preg_match() with negative lookbehind and negative lookahead:

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

试试这个,使用 preg_match_all

$str = 'Just 44 4 test 444';
preg_match_all('!\d+!', $str, $matches);
 // print_r($matches);


if (in_array("4", $matches[0])){
    echo "Match found";
  }
else
{
  echo "Match not found";
}

DEMO