REGEX for Matching A String Exactly

2019-08-20 07:02发布

I'm having a bit of trouble matching a string using REGEX (PHP).

We have this code:

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

We have this REGEX:

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

However, this is also matching ALL paragraph tags on the string - not just the ones containing the IFRAME tags. How can we only match the P tags containing IFRAME?

We also want to match this code using the same REGEX:

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

Notice that there are no line breaks and less whitespace (in the P tag).

How can we achieve this? I'm a little new to REGEX.

Thank you for your help in advance.

标签: php regex iframe
3条回答
Bombasti
2楼-- · 2019-08-20 07:14
<p.*?>.*?<iframe.*?><\/iframe><\/p>

Try this.See demo.

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);

Just make your * greedy operators non greedy *?

查看更多
家丑人穷心不美
3楼-- · 2019-08-20 07:28

Match only whitespace characters in between <p> and <iframe>:

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

I also added exclude for > instead of any char (.).

查看更多
欢心
4楼-- · 2019-08-20 07:33

Use [^>]* instead of .* like:

/<p[^.]*>[^<]*<iframe[^>]*><\/iframe><\/p>/is
查看更多
登录 后发表回答