regex php - find things in div with specific ID

自作多情 提交于 2019-12-10 19:59:23

问题


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.


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




回答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 = "<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).




回答3:


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



来源:https://stackoverflow.com/questions/7079861/regex-php-find-things-in-div-with-specific-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!