如何使用RegEx获取此信息?

时间:2011-06-05 20:12:41

标签: php regex

说我有这个:

<li class="one"><strong>String here: </strong><span class="one">&nbsp;
                                 <!--googleoff: all--> 
                                 <strong>STRING TO GRAB</strong> 
                                 <!--googleon: all--> 
                                 </span></li> 

如何使用RegEx高效抓取STRING TO GRAB?请注意,这不是页面上的唯一文字,因此/<strong>(.*)<\/strong>/无效。

由于

2 个答案:

答案 0 :(得分:3)

有两种方式。

Dom类:如果html是一种不错的类型,请使用PHP的dom类。

请参阅: - http://www.php.net/manual/en/domxpath.query.php - http://www.php.net/manual/en/domdocument.loadhtml.php

<强>正则表达式  如果它不是真正有效的html或dom加载不起作用,也许正则表达式是一个很好的解决方案。

我假设&lt;! - googleoff:all - &gt;总是存在,这可能有效,如果没有,也许你可以提供更多关于字符串特异性的评论:

$string = "yourhtmlstring";
$matches = array();
preg_match('/<!--googleoff: all-->\s+?<strong>(.+)<\/strong>\s+?<!--googleon: all-->/', $string, $matches)
var_dump($matches);

最终提示 要进一步测试正则表达式:http://tinyurl.com/6gy6584

答案 1 :(得分:0)

正如另一个回答所说,正则表达式不是html(或xml)的最佳答案

/<strong>(.+?)<\/strong>/

请注意?使正则表达式非贪婪