【问题标题】:php preg_match_all not specific numberphp preg_match_all 不是特定数字
【发布时间】:2012-08-23 23:56:03
【问题描述】:

我想从 569048004801 等数字字符串中排除特定数字 4800。 我为此使用 php 和方法 preg_match_all 我尝试过的一些模式示例:

/([^4])([^8])([^0])([^0])/i
/([^4800])/i

【问题讨论】:

  • [^4800][^480] 相同,意思是“在任何特定的单个位置,不允许 4、8 或 0。/i 也毫无意义。没有这样的事情作为大写数字。

标签: php regex preg-match-all


【解决方案1】:

如果你只是想看一个字符串是否包含4800,你不需要正则表达式:

<?php

$string = '569048004801';

if(strpos($string,'4800') === false){
  echo '4800 was not found in the string';
}
else{
  echo '4800 was found in the string'; 
}

documentation here中有关strpos的更多信息

【讨论】:

    【解决方案2】:

    如果您只是想从字符串中删除4800,使用str_replace 会更容易:

    $str = '569048004801';
    $str = str_replace('4800', '', $str);
    

    另一方面,如果你的意思是你想知道一个特定的数字字符串是否包含4800,这将为你测试:

    $str = '569048004801';
    
    if (preg_match_all('/4800/', $str) > 0) {
        echo 'String contains 4800.';
    } else {
        echo 'String does not contain 4800.';
    }
    

    【讨论】:

      【解决方案3】:
      /([^4])([^8])([^0])([^0])/i
      

      这实际上是说,不是“4800”的四个字符序列。关闭。

      /([^4800])/i
      

      这实际上是说,不是“4”、“8”或“0”的单个字符

      假设您要捕获一个不包含“4800”的数字,我想您可能想要

      /(?!\d*4800)\d+/i
      

      这表示,首先检查我们没有在某处查看带有“4800”的数字字符串,如果是这种情况,请捕获数字字符串。它被称为“负前瞻断言”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        相关资源
        最近更新 更多