【问题标题】:Check if string ends with number and get the number if true检查字符串是否以数字结尾,如果为真则获取数字
【发布时间】:2016-03-22 12:05:36
【问题描述】:

如何检查字符串是否以数字结尾,如果为真,则将数字推送到数组(例如)?我知道如何检查字符串是否以数字结尾,我是这样解决的:

$mystring = "t123";

$ret = preg_match("/t[0-9+]/", $mystring);
if ($ret == true)
{
    echo "preg_match <br>";
    //Now get the number
}
else
{
    echo "no match <br>";
}

让我们假设所有字符串都以字母 t 开头,并与一个数字组合,例如t1,t224, t353253 ...

但是,如果有一个,我怎么能删掉这个数字呢?在我的代码示例中,字符串末尾有123,我怎样才能将其剪切出来,例如将其推送到带有array_push 的数组?

【问题讨论】:

    标签: php preg-match


    【解决方案1】:
    $number = preg_replace("/^t(\d+)$/", "$1", $mystring);
    if (is_numeric($number)) {
        //push
    }
    

    这应该为您提供尾随数字。只需检查它是否为数字,将其推送到您的数组中

    示例:https://3v4l.org/lYk99

    编辑:

    请意识到这不适用于像 t123t225 这样的字符串。如果您需要支持这种情况,请改用此模式:/^t.*?(\d+)$/。这意味着它会尝试捕获以数字结尾的所有内容,忽略t 和数字之间的所有内容,并且必须以t 开头。

    示例:https://3v4l.org/tJgYu

    【讨论】:

    • 很好的答案谢谢。不,字符串都是这样的t123 但是感谢您提供有关如何解决其他变体的信息。
    【解决方案2】:

    首先,您的正则表达式有点错误(可能是错字) - 但要回答您的问题,您可以使用后向和匹配数组,如下所示:

    $test = 't12345';
    
    if(preg_match('/(?<=t)(\d+)/', $test, $matches)){
    
        $result = $matches[0];
    
        echo($result);
    }
    

    【讨论】:

      【解决方案3】:

      您应该使用 preg_match 中的第三个参数来获取匹配项,并且应该有数字并像这样更改您的正则表达式:([0-9]+)

      所以代码应该是这样的:

      $mystring = "t123";
      
      $ret = preg_match("/([0-9]+)/", $mystring, $matches);
      if ($ret == true)
      {
          print_r($matches); //here you will have an array of matches. get last one if you want last number from array.
          echo "prag_match <br>";
      }
      else
      {
          echo "no match <br>";
      }
      

      【讨论】:

        【解决方案4】:

        preg_match 函数中再添加一个参数,我想建议一些其他正则表达式,以便从任何字符串的最后一个获取数字。

        $array = array();
        $mystring = "t123";
        
        $ret = preg_match("#(\d+)$#", $mystring, $matches);
        
        
        array_push($array, $matches[0]);
        
        $mystring = "t58658";
        
        $ret = preg_match("#(\d+)$#", $mystring, $matches);
        
        array_push($array, $matches[0]);
        
        $mystring = "this is test string 85";
        
        $ret = preg_match("#(\d+)$#", $mystring, $matches);
        
        array_push($array, $matches[0]);
        
        print_r($array);
        

        输出

        Array
        (
            [0] => 123
            [1] => 58658
            [2] => 85
        )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多