PHP preg_match_all html

删除回忆录丶 提交于 2019-12-08 09:39:53

问题


how can i create a preg_match_all regex pattern for php to give me this code?

<td class="class2">&nbsp;</td>
<td class="class2" align="right"><span class="DarkText">I WANT THIS TEXT</span></td>

To get me the text inside the span class? thanks!


回答1:


You can use:

preg_match_all("!<span[^>]+>(.*?)</span>!", $str, $matches);

Then your text will be inside the first capture group (as seen on rubular)

With that out of the way, note that regex shouldn't be used to parse HTML. You will be better off using an XML parser, unless it's something really, really simple.




回答2:


It's tough to write Regexes that parse HTML perfectly. Instead, use an HTML parser like this one: http://simplehtmldom.sourceforge.net/. It is easy to use and I have recommended it on here several times.




回答3:


You can also not use ! at start and end, and use much simpler code with T-Regx

$pattern = "<span[^>]+>(.*?)</span>"; // no delimiters :)

$string = '
<td class="class2">&nbsp;</td>
<td class="class2" align="right"><span class="DarkText">I WANT THIS 
TEXT</span></td>
';

Then just use match()->group():

$text = Pattern::of($pattern)->match($string)->group(1)->first();

$text // 'I WANT THIS TEXT'

Check it online: https://regex101.com/r/nxTvS1/1



来源:https://stackoverflow.com/questions/3722770/php-preg-match-all-html

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