【问题标题】:REGEX for Matching A String Exactly用于精确匹配字符串的正则表达式
【发布时间】:2015-01-08 12:47:07
【问题描述】:

我在使用 REGEX (PHP) 匹配字符串时遇到了一些问题。

我们有这个代码:

<p style="text-align: center; ">
    <iframe height="360" src="http://example.com/videoembed/9338/" frameborder="0" width="640"></iframe></p>

我们有这个正则表达式:

/<p.*>.*<iframe.*><\/iframe><\/p>/is

但是,这也匹配字符串上的所有段落标记 - 不仅仅是包含 IFRAME 标记的那些。怎么才能只匹配包含IFRAME的P标签呢?

我们还想使用相同的 REGEX 匹配此代码:

<p style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="360" src="http://example.com/videoembed/9718/" width="640"></iframe></p>

请注意,没有换行符和更少的空格(在 P 标记中)。

我们怎样才能做到这一点?我对 REGEX 有点陌生。

提前感谢您的帮助。

【问题讨论】:

  • 您绝对应该在此任务中使用正则表达式,而应使用 XML 解析器,例如 XML ParserSimpleXML,或 HTML 解析器,例如 @ 987654323@.
  • 这可能无法回答您的问题,但可以解决您停止使用正则表达式解析 (x)html 的问题。您可能想看看这个:php.net/manual/de/book.simplexml.phpstackoverflow.com/questions/1732348/…
  • 进一步鼓励使用 HTML 解析器而不是正则表达式:htmlparsing.com
  • 感谢您提供您的 cmets。我肯定会研究 PHP 中的 HTML 解析而不是正则表达式。

标签: php regex iframe


【解决方案1】:

仅匹配&lt;p&gt;&lt;iframe&gt; 之间的空白字符:

/<p[^>]*>\s*<iframe[^>]*><\/iframe>\s*<\/p>/is

我还为 &gt; 添加了排除,而不是任何字符 (.)。

【讨论】:

    【解决方案2】:
    <p.*?>.*?<iframe.*?><\/iframe><\/p>
    

    试试这个。查看演示。

    https://regex101.com/r/sH8aR8/30

    $re = "/<p.*?>.*?<iframe.*?><\\/iframe><\\/p>/is";
    $str = "<p style=\"text-align: center; \">\n <iframe height=\"360\" src=\"http://example.com/videoembed/9338/\" frameborder=\"0\" width=\"640\"></iframe></p>\n\n<p style=\"text-align: center;\"><iframe allowfullscreen=\"\" frameborder=\"0\" height=\"360\" src=\"http://example.com/videoembed/9718/\" width=\"640\"></iframe></p>";
    
    preg_match_all($re, $str, $matches);
    

    只要让你的 * 贪婪运营商 non greedy *?

    【讨论】:

      【解决方案3】:

      使用 [^>]* 代替 .* 像:

      /<p[^.]*>[^<]*<iframe[^>]*><\/iframe><\/p>/is
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-18
        • 1970-01-01
        相关资源
        最近更新 更多