Jump to content

Simple preg match with <p> tags


a1amattyj

Recommended Posts

Hello,

 

Trying to get all content within paragraph tags. Im using:

 

preg_match("#<p>(.*)</p>#i", $contents, $match);

 

There are around 8 paragraphs on this page, but it only matches two - and thats the first <p> tag with the last </p> tag. Not to sure what I should change (.*) too?

 

Thanks

Link to comment
Share on other sites

Well, you also have the problem that your regex is "greedy". Even if you used preg_match_all() it would only return one result - everything from the very first "<p>" to the very last "</p>". You need to make the expression "non-greedy" so that it will return each instance of "<p>" to the next "</p>". It is the asterisk (*) that is behaving in a greedy manner in that expression. One way to make it non-greedy is to add a question mark (?) after the asterisk.

 

Also, I think you have to escape the forward slash. And I would also add some handling for the opening paragraph tag in case there are additional attributes for the paragraph tag such as a class or style attribute.

 

Try this:

preg_match_all("#<p[^>]*>(.*?)<\/p>#i", $contents, $matches);

Link to comment
Share on other sites

good catch mjdamato thank you, only thing i'll add is the forward slash will not need to be escaped since the OP is using the # delimiter

 

preg_match_all("#<p[^>]*>(.*?)</p>#i", $contents, $matches);

 

nothing major though

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.