Jump to content

Matching more than one line


Mycotheologist

Recommended Posts

SOLVED: I solved the problem by removing the U modifier but I have no idea why it worked. I don't know what U does. I don't know what s does either but this won't work without it.

 

Lets say I have this HTML page:

 

<h1>BLAH BLAH BLAH</h1>

sdfasdf

<p>
fsadfsk pspfj 
spdjfsdfj
psadfpo
</p>

<p>
244524
35234546
1164146sdfgsa
</p>

 

and I need to load everything thats inside the <p> tags into an array. Heres the code I tried using:

 

if (preg_match_all('/ <p>(.*?)<p>:/msU',$of,$matches)) { 
$paragraph = $matches[1][0];

but it won't work. If I echo $paragraph, it will output this:

fsadfsk pspfj

spdjfsdfj

psadfpo

</p>

 

<p>

244524

35234546

1164146sdfgsa

rather than just outputting the first paragraph which should be:

fsadfsk pspfj

spdjfsdfj

psadfpo

 

What am I doing wrong?

Link to comment
https://forums.phpfreaks.com/topic/265718-matching-more-than-one-line/
Share on other sites

Basically the issue is that you have .*? which makes for an ungreedy match-all, but the U modifier inverts that and makes it greedy, so it is matching everything up to the last closing p tag.  I see you have another thread where you ask about greedy vs. non-greedy, and more detailed explanation was given there. 

 

For your other modifiers...

 

s modifier: By default, the . (dot) metachar will match most anything.  One thing it does not match is new line chars, the s modifier makes the  . (dot) also match newline chars, which you need since you are trying to grab the stuff between your p tags, which spans multiple lines. 

 

m modifier: You don't actually need this for your pattern.  You only need this if your content spans multiple lines (which it does), but you are trying to match individual lines (by using anchor metachars).  Since that is not something you are doing in your pattern, you can remove this.

 

 

 

 

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.