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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测