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

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.