Jump to content

regex + php, match new line html


citricsquid

Recommended Posts

Hello, regex makes my head hurt.

 

If I have:

<div id="this">HELLO!</div>

and I want to find out what's between <div id="this"></div> I'd just do:

preg_match('%<div id="this">(.*?)</div>%sm', $string, $result);

and it works fine, but if I have:

<div id="this">
<div id="subthis">
hello
</div>
</div>

 

and I want to get the contents of the div "this", it doesn't work. I'm assuming this is because of newlines and any whitespace. How would I avoid this?

Link to comment
https://forums.phpfreaks.com/topic/177701-regex-php-match-new-line-html/
Share on other sites

It makes my head hurt also. In your particular case. The question mark makes the search lazy meaning it will exit at the first occurance of </div> which is obviously not what your after. I don't have experience of working with nested tags though so I'm not sure of the solution. In your example remove the question mark will work, but since there could well be another div outside that it's not a solution. You'd potentially have to use a recursive call to preg_match. In your case however it could potentially be easier using a method other than regular expressions. Depends on your requirements, but there's potentially a way to just parse it as an xml dom.

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.