开发者

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 similar expressions that return exactly what I want.

However, I can't get this particular bit to return what I want, so maybe someone can help me.

I have a div with a specific ID "user-sub-commhome" - I want to pull out the text from within that div. The text is surrounded by tags but I can easily use strip_tags to get those gone. I'm using regex to try and pull the data out.

Here is my code:

$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;

I've tried changing things with no success, nothing seems开发者_开发知识库 to work to echo anything. So I'm hoping some power that be who is much more experienced with regex can help.


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.


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 = "<div id=\"user-sub-summary\">Summary</div>
<div id=\"user-sub-commhome\"><em>Commercial</em></div>
<div id=\"whatever\">whatever</div>";

or this:

$intro = '<div id="user-sub-summary">Summary</div>
<div id="user-sub-commhome"><em>Commercial</em></div>
<div id="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).


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜