【问题标题】:php preg_match get numbers between two stringsphp preg_match 获取两个字符串之间的数字
【发布时间】:2013-12-28 21:25:04
【问题描述】:

您好我开始学习 php 正则表达式并遇到以下问题: 我需要提取 $string 中的数字。 我使用的正则表达式返回“NULL”。

$string = 'Clasificación</a> (2194)  </li>';
$regex = '/Clasificación</a>((.*?))</li>/';
preg_match($regex , $string, $match);
var_dump($match);

提前致谢。

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    您的正则表达式存在三个问题:

    • 您没有转义正斜杠。您正在使用正斜杠作为分隔符,因此如果您想将其用作表达式中的文字字符,则需要对其进行转义
    • ((.*?)) 没有做你认为的事情。它创建了两个捕获组——一个嵌套在另一个内部。我假设,您正在尝试捕获括号内的内容。为此,您需要转义 () 字符。表达式将变为:\((.*?)\)
    • 您的表达式不处理空格。在您给出的字符串中,&lt;/a&gt; 和数字开头之间有空格 - &lt;/a&gt; (2194)。要忽略空格并仅捕获数字,您需要使用\s(匹配任何空格字符)。为此,您需要写\s*\((.*?)\)\s*

    修正上述所有错误后的最终正则表达式将如下所示:

    $regex = '~Clasificación</a>\s*\((.*?)\)\s*</li>~';
    

    完整代码:

    $string = 'Clasificación</a> (2194)  </li>';
    $regex = '~Clasificación</a>\s*\((.*?)\)\s*</li>~';
    preg_match($regex , $string, $match);
    var_dump($match);
    

    输出:

    array(2) {
      [0]=>
      string(32) "Clasificación (2194)  "
      [1]=>
      string(4) "2194"
    }
    

    Demo.

    【讨论】:

      【解决方案2】:

      您忘记在您的正则表达式中使用空格 /,因为您使用 / 作为分隔符:

      $regex = '/Clasificación<\/a>((.*?))<\/li>/';
      //        ^ delimiter    ^^               ^ delimiter
      //                       ^^ / in a string which is escaped
      

      另一种方法是更改​​该分隔符,然后您就不必转义它:

      $regex = '#Clasificación<\/a>((.*?))<\/li>#';
      

      请参阅PHP documentation 了解更多信息。

      【讨论】:

        【解决方案3】:

        您必须转义出要匹配的特殊字符:

        $regex = '/Clasificación<\/a> \((.*?)\) <\/li>/'
        

        并且可能想让你的匹配在重要的地方更具体一点(取决于你的用例)

        $regex = '/Clasificación<\/a>\s*\(([0-9]+)\)\s*<\/li>/'; 
        

        这将允许在 (1234) 之前或之后有 0 个或多个空格,并且仅当 () 中只有数字时才匹配

        我刚刚在 php 中试过这个:

        php > preg_match($regex , $string, $match);
        php > var_dump($match);
        array(2) {
          [0]=>
          string(30) "Clasificacin</a> (2194)  </li>"
          [1]=>
           string(4) "2194"
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-12
          • 1970-01-01
          • 2012-11-13
          • 2012-12-28
          • 1970-01-01
          • 1970-01-01
          • 2010-11-29
          相关资源
          最近更新 更多