【问题标题】:Check if string has a specific number, not digit [duplicate]检查字符串是否具有特定数字,而不是数字 [重复]
【发布时间】:2022-01-10 01:06:14
【问题描述】:

这就是我所拥有的:

$a = '3,24,57';

if (strpos($a, '7') == true) {
    echo 'number found';
}

由于数字 57,代码将返回“找到的数字”,但字符串中没有数字 7。我怎样才能使这项工作以仅在字符串如下时才返回 true 的方式工作:“3,7,24,57”

谢谢

【问题讨论】:

  • 是的,explode() 可能是最好的选择

标签: php string find


【解决方案1】:

就这样试试吧。

$array = explode(",", $a);
if (in_array("7", $array )) {
    echo 'number found';
}

【讨论】:

    【解决方案2】:

    试试这个:

    $a = '3,24,57';
    
    if (strpos($a, ',7,') == true || strpos($a, '7,') == true || strpos($a, ',7') == true) {
        echo 'number found';
    }
    

    【讨论】:

    • 嗯,它也可以,但我更喜欢其他的 ;) 感谢您的回复。
    【解决方案3】:

    在您的情况下,请使用以下正则表达式: 像这样:

    <?php
    
      $a = '3,24,57';
      $find = 7;
      if (preg_match("/(?<!\d){$find}(?!\d)/", $a)) {
        echo "number found";
      } else {
        echo "number not found";
      }    
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 2017-02-23
      • 2018-09-25
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2018-09-28
      • 1970-01-01
      相关资源
      最近更新 更多