Regular expression to match HTML <p> tag using PHP
I have content like this
<p>some content, paragraph 1</p> <p>some content, paragraph 2</p> <p>some content, paragraph 3</p> I would like to return the first paragraph ie
<p>some content, paragraph 1</p> Can someone help me with regex code?'<p>(.*.)</p>' doesn't seem to work
you can do it like this:
if (preg_match('%(<p[^>]*>.*?</p>)%i', $subject, $regs)) { $result = $regs[1]; } else { $result = ""; } You check your string for regular expression, if there is any match, you get the first and only the first, if not. $ result will be an empty string.
If you need to get more than the first result, you can iterate over the $ regs array. And you need to find any other tag that changes the regular expresión to process it, for example, to find the IMAGE tags that you use:
(<img[^>]*>.*?</img>) EDIT: If you process line by line (only with the tag you are looking for), you can put ^ ... $ around the expression to match the complete line, for example:
if (preg_match('%^(<p[^>]*>.*?</p>)$%im', $subject, $regs)) { $result = $regs[1]; } else { $result = ""; } Hth, Regards.
Preventing the inclusion of the <pre> tag, may use:
if (preg_match('/(<p(>|\s+[^>]*>).*?<\/p>)/i', $subject, $regs)) { $result = $regs[1]; } else { $result = ""; } if (preg_match("/\b1\b/i", "some content, paragraph 1")) { echo "A match was found."; } else { echo "A match was not found."; } Where 1 is an agreed term ...
Is that any help?