【问题标题】:Regular Expression Tester says expression works but preg_match fails正则表达式测试器说表达式有效,但 preg_match 失败
【发布时间】:2013-11-30 05:04:24
【问题描述】:

我正在尝试从字符串中提取 em 标记。在 http://www.phpliveregex.com/ 上,我的正则表达式有效,但在我的代码中它返回 0(未找到匹配项)。

$regex = "/<em class=\"correct_response\".*\/em>/";
echo preg_match($regex, $string);
/* sample values for the data in $string are 

    toggle('clue_J_1_1', 'clue_J_1_1_stuck', '<em class="correct_response">3M</em><br /><br /> <table width="100%"><tr><td class="right">Ashok</td></tr></table>')
    toggle('clue_J_2_2', 'clue_J_2_2_stuck', '<em class="correct_response">Confucius</em><br /><br /><table width="100%"><tr><td class="right">Ashok</td></tr></table>')

*/

我做错了什么?谢谢。

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    您需要转义正在转义 /em&gt; 中正斜杠的反斜杠,因为您使用双引号分隔字符串。

    $regex = "/<em class=\"correct_response\".*\\/em>/";
    

    这只是一个问题,因为您的字符串使用了双引号。以下使用单引号也应该可以工作并且需要更少的字符:

    $regex = '/<em class="correct_response".*\/em>/';
    

    如果您不想担心必须转义正斜杠,可以使用其他delimiters,例如#

    $regex = '#<em class="correct_response".*/em>#';
    

    【讨论】:

      【解决方案2】:

      您使用了正确的正则表达式!我也刚刚测试确认。

      你做错的是你使用 preg_match 函数的方式。

      阅读 PHP 手册。

      这是经过全面测试的代码,只需复制粘贴并在空白 php 文件中尝试:

      <?php
      $regex = "/<em class=\"correct_response\".*\/em>/";
      $string = "toggle('clue_J_1_1', 'clue_J_1_1_stuck', '<em class=\"correct_response\">3M</em><br /><br /> <table width=\"100%\"><tr><td class=\"right\">Ashok</td></tr></table>')";
      preg_match($regex,$string,$matches);
      echo $matches[0];
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-23
        • 2011-11-19
        • 1970-01-01
        • 1970-01-01
        • 2012-01-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多