Skip to content Skip to sidebar Skip to footer

Regex Php - Find Things In Div With Specific Id

I'm sure this is an easy one, and as much as I've googled and searched here on SO - I can't seem to figure out what is wrong with this. I have other areas on this page where I use

Solution 1:

Your code works for me if you change the enclosing doublequotes around $intro to single quotes:

$intro= '<div id="user-sub-summary">Summary</div>
<div id="user-sub-commhome"><em>Commercial</em></div>
<div id="whatever">whatever</div>';

$regex= '#\<div id="user-sub-commhome"\>(.+?)\<\/div\>#s';
preg_match($regex, $intro, $matches);
$match=$matches[0];
echo $match;

You might want to read some famous advice on regular expressions and HTML.

Solution 2:

i won't explain why using regular expressions to parse php is a bad idea. i think the problem here is you don't have error_reporting activated or you're simply not looking into your error-log. defining the $intro-string the way you do should cause a lot of problems (unexpectet whatever / unterminatet string). it should look like this:

$intro = "<divid=\"user-sub-summary\">Summary</div><divid=\"user-sub-commhome\"><em>Commercial</em></div><divid=\"whatever\">whatever</div>";

or this:

$intro = '<divid="user-sub-summary">Summary</div><divid="user-sub-commhome"><em>Commercial</em></div><divid="whatever">whatever</div>';

if you're using double quotes inside a double-quotet string, you have to mask them using a backslash (\). anoter way would be to use single-quotes for the string (like in my second example).

Solution 3:

In your sample code $matches[0] contains all matched part, not the capturing group. The capturing group is in $matches[1]

Post a Comment for "Regex Php - Find Things In Div With Specific Id"