Jump to content

[SOLVED] PHP Spider and Regular Expressions


jjacquay712

Recommended Posts

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.

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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.