【问题标题】:php string how to find one number in a string of numbers [duplicate]php字符串如何在一串数字中找到一个数字[重复]
【发布时间】:2012-08-30 23:35:03
【问题描述】:

可能重复:
How can I check if a word is contained in another string using PHP?

我希望有一些PHP代码来检查某个数字是否出现在数字字符串中,例如如何检查数字7是否出现在数字3275中?

我已经尝试过 strcmp 但我无法解决这个问题:(

【问题讨论】:

    标签: php


    【解决方案1】:
    if(stristr('3275', '7') !== false)
    {
      // found
    }
    

    【讨论】:

    • if(stristr("3275","7") !== false) { // found }
    【解决方案2】:

    这样试试

    $phno = 1234567890;
    $collect = 4;
    $position = strpos($phno, $collect);
    
    if ($position)
        echo 'The number is found at the position'.$position;   
    else
        echo 'Sorry the number is not found...!!!';
    

    【讨论】:

      【解决方案3】:

      strpos()是你的朋友,php不是强类型的,所以你可以把数字当作字符串。

      $mystring = 3232327;
      $findme   = 7;
      $pos = strpos($mystring, $findme);
      
      if ($pos === false) {
          echo "The number '$findme' was not found in the number '$mystring'";
      } else {
          echo "The number '$findme' was found in the number '$mystring'";
          echo " and exists at position $pos";
      }
      

      【讨论】:

        【解决方案4】:

        试试这个代码:

        $pos = strrpos($mystring, "7");
        if ($pos === false) { // note: three equal signs
            // not found...
        }
        else{
            //string found
        }
        

        【讨论】:

        • 请注意,'strrpos' 查找最后一次出现,而 'strpos' 查找第一次出现。这两个函数都适用于这个用例。
        【解决方案5】:

        http://us3.php.net/strpos

        int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
        

        在 haystack 字符串中查找第一次出现 needle 的数字位置。

        确保在比较返回值时使用“!== false”以查看它是否存在(否则 7325 将返回位置 0 和 0 == false) - === 和 !== 是比较值和类型(布尔与整数)

        【讨论】:

          【解决方案6】:

          看看strpos;您可以使用它来查找子字符串在字符串中出现的位置(以及,通过扩展,是否出现)。请参阅第一个示例了解如何正确进行检查。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-08-02
            • 2011-01-23
            • 2014-01-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-08-22
            • 1970-01-01
            相关资源
            最近更新 更多