Jump to content

[SOLVED] PHP Spider and Regular Expressions


jjacquay712

Recommended Posts

The only problem with your regex is that it won't work if there is a '<' inside the <p> tags. This should work:

 

preg_match('/<p>(.*?)<\/p>/', $text, $matches);
$p_tag_text = $matches[1];

 

a more robust regex:

 

~<\s*p\b[^>]*>(.*?)<\s*/\s*p\s*>~is"

 

however if you have something like

 

<p> some text

 

<p>More text</p>

 

Final text

</p>

 

You'll only capture up to "More Text" ... which I imagine might not be what you want.  Better approach would be to use tidy or the dom processing libraries to access the first P you find so you can properly get all it's children.

Link to comment
Share on other sites

I need to extract the text out of the first <p> tag in a web page for my spider. Im using preg match all with this pattern: /<p>([^<]*)<\/p> but its not working. I have no idea how to use Regular Expressions, so any help would be appreciated.

 

there's no need to use regex, if you are not familiar. There are many string methods you can use in PHP, such as strpos

$startpos = strpos($data,"<p>");
$endpos = strpos($data,"</p>");
echo substr($data,$startpos+strlen("<p>"),$endpos - $startpos);

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.