duan19805 2016-08-23 08:46
浏览 68
已采纳

PHP中的正则表达式“不匹配数字”

I would like to check if a string is in another string with comma separated. I've write some code and it work like this...

$find_number = '3'
$string_to_search = '1,3,124,12'
preg_match('/[^0-9]'.$find_number.'[^0-9]/', string_to_search);
//match

$find_number = '4'
$string_to_search = '1,3,124,12'
preg_match('/[^0-9]'.$find_number.'[^0-9]/', string_to_search);
//not match

Which is what I expected. The problem is that the first and last string can't recognized in this expression. What did I do wrong?

  • 写回答

2条回答 默认 最新

  • douyu4822 2016-08-23 08:52
    关注

    You need to make sure to check if there are no digits on both sides of the $find_number, and that is why you need (?<!\d) / (?!\d) lookarounds that do not consume text before and after the number you need to match allowing to check the first and last items. The [^0-9] in your pattern are negated character class instances, that require a character other than a digit before and after the find_number. The lookarounds will just fail the match if there is a digit before ((?<!\d) negative lookbehind) or after (with (?!\d) negative lookahead) the find_number. See below:

    $find_number = '3';
    $string_to_search = '1,3,124,12';
    if (preg_match('/(?<!\d)'.$find_number.'(?!\d)/', $string_to_search)) {
        echo "match!";
    }
    

    See the PHP demo.

    An alternative is to use explode with in_array:

    $find_number = '3';
    $string_to_search = '1,3,124,12';
    if (in_array($find_number, explode(",", $string_to_search))) {
        echo "match!";
    }
    

    See another PHP demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题