douna2633 2016-10-17 03:01
浏览 26
已采纳

php在字符串中查找字符但单独使用该字符

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

  • 写回答

2条回答 默认 最新

  • douwa0280 2016-10-17 03:07
    关注

    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"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?