REGEX for Matching A String Exactly

2019-08-20 06:29发布

问题:

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.

回答1:

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 (.).



回答2:

<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:

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

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


标签: php regex iframe