Php 用于精确匹配字符串的正则表达式

Php 用于精确匹配字符串的正则表达式,php,regex,iframe,Php,Regex,Iframe,我在使用正则表达式(PHP)匹配字符串时遇到了一些问题 我们有以下代码: <p style="text-align: center; "> <iframe height="360" src="http://example.com/videoembed/9338/" frameborder="0" width="640"></iframe></p> /<p.*>.*<iframe.*><\/iframe>

我在使用正则表达式(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
<p style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="360" src="http://example.com/videoembed/9718/" width="640"></iframe></p>

我们有这个正则表达式:

<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
<p style="text-align: center;"><iframe allowfullscreen="" frameborder="0" height="360" src="http://example.com/videoembed/9718/" width="640"></iframe></p>
/.*/is
但是,这也会匹配字符串上的所有段落标记,而不仅仅是包含IFRAME标记的段落标记。我们如何只匹配包含IFRAME的P标记

我们还希望使用相同的正则表达式匹配此代码:

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

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

我们如何才能做到这一点?我对REGEX有点陌生


提前感谢您的帮助。

只匹配
之间的空白字符:

/<p[^>]*>\s*<iframe[^>]*><\/iframe>\s*<\/p>/is
/]*>\s*]*>\s*/is
我还为
添加了排除,而不是任何字符(
)。

*?
试试这个。看演示

$re=“/.*?/is”;
$str=“

\n

\n\n

”; 预匹配全部($re,$str,$MATCHS);

只需让您的
*
贪婪运算符
非贪婪运算符
*?
使用[^>]*而不是。*即可,如:

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

此任务绝对不应使用正则表达式,而应使用XML解析器(如or)或HTML解析器(如)。这可能无法回答您的问题,但停止解析(x)可能会解决您的问题您可能想看看这个:并且进一步鼓励您使用html解析器而不是正则表达式:感谢您提供您的评论。我肯定会研究PHP中的html解析,而不是正则表达式。