【问题标题】:php regex via using preg_match通过使用 preg_match 的 php 正则表达式
【发布时间】:2013-04-06 06:23:26
【问题描述】:

我有一个由字符和数字组成的变量$play。例如:

$play = "blah05"

我如何使用preg_match() 只获得 05? 我的$regexp 正确吗?

$regexp = "/^[^0-9]/";
if (preg_match($regexp, $play, $matches)) {
   echo "matches[0]";
}

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    如果你想从最后得到数字,正则表达式应该是这样的:

    $regexp = '/(\d+)$/';

    如果你想从字符串中的任何地方获取数字:

    $regexp = '/(\d+)/';

    只需发送var_dump($matches); 即可查看结果并选择最适合您的选项。

    if (preg_match($regexp, $play, $matches)) {
       var_dump($matches);
    }
    

    【讨论】:

      【解决方案2】:

      试试:

      $regexp = "/([0-9]+)$/";
      if (preg_match($regexp, $play, $matches)) {
          echo $matches[1];
      }
      

      这会捕获字符串末尾有数字的那些,如果你想捕获在字符串中任何位置有数字的那些,请删除 $。

      【讨论】:

        【解决方案3】:
        $regexp = "/[0-9]+/";
        if (preg_match($regexp, $play, $matches)) {
           echo $matches[0];
        }
        

        [0-9] 是数字。加上 + 你至少匹配一个数字(尽可能多)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-05
          • 2014-06-28
          • 1970-01-01
          • 2012-01-14
          • 1970-01-01
          相关资源
          最近更新 更多