Jump to content

preg _match ?? is there something I am doing wrong.


Recommended Posts

Hello,

 

I have a piece of code which contains the following:

 

<h1 class="productTitle"> Solar grid</h1>
					<div class="image"> <img src="../images/IGT.jpg" alt="Solar grid" /> </div>

					<div class="story">
XXX A BUNCH OF PLAIN TEXT XXX

		</div>

 

and I am trying to parse a bunch of similar pages:

 

I have the following preg_match code:

 

$title = '/class="productTitle">(.+?)<\/h1>/';
$description = '/class="story">(.+?)<\/div>/';


preg_match($title,$source,$match1);

preg_match($description,$source,$match2);

 

The two search terms are identical, but only the top preg_match is returning a value in $match1, $match2 is empty.

 

Is there something about this preg_match code I am missing?? Is is because there are other </div>'s on the page and not just one, like there are with the h1 tag??

 

Any help would be awesome

 

James

 

Your second pattern lacks the s modifier, so (.+?) will not get far, as it will not include newlines. I suspect this is something along the lines you are after:

 

Example:


$source = <<<EOF
<h1 class="productTitle"> Solar grid</h1>
                  <div class="image"> <img src="../images/IGT.jpg" alt="Solar grid" /> <>


                  <div class="story">
XXX A BUNCH OF PLAIN TEXT XXX


         <>
EOF;

$title = '#class="productTitle">(.+?)</h1>#';
$description = '#class="story">(.+?)<>#s';


preg_match($title,$source,$match1);
echo $match1[1] . "<br />\n";
preg_match($description,$source,$match2);
echo $match2[1];

 

Granted, I think it would be better to use DOM for this sort of thing (regex can be easily 'fooled' if the pattern isn't well structured).

 

EDIT - Seems like the closing tags in the snippet are not displaying properly in the snippet post.. Will see if this is a reproducable bug and if so, will notify the staff about it.

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.