如何使用 preg_match() 提取文本


how to extract text using preg_match()?

可能的重复项:
如何使用PHP解析和处理HTML?

我将以下文本存储在变量$new

<div class="img">
<span style="float:left; color:#666;">1.&nbsp;&nbsp;</span>
<a href="/Books/info/J-R-R-Tolkien/The-Lord-of-the-Rings/0618640150.html?utm_term=lord+of+the+ring_1_1">
<img src="http://cdn-img-b-tata.infibeam.net/img/6a53fabc/157/0/9780618640157.jpg?wid=90&hei=113" width="90" height="113" border="0">
</a>
</div>
<span class="title">
<h2 class="simple"><a href="/Books/info/J-R-R-Tolkien/The-Lord-of-the-Rings/0618640150.html?utm_term=lord+of+the+ring_1_1"><em>Lord</em> of the <em>Rings</em></a></h2>
&nbsp;By
<a href="/Books/search?author=J R R Tolkien" style="font-size:12px; text-decoration:none;">J R R Tolkien</a>
<span style="color:#666666; font-size:11px;">[Paperback 2005, 50th Edition]</span>
</span>
<div class="price" style="line-height:30px;margin-top:0px;">

我必须提取从1.&nbsp<div的文本。我已经尝试了所有可能的解决方案,但没有成功。

这应该有效

$ret = preg_replace ("#1'.&nbsp(.+)<div#isU", "$1", $new);

$new包含您的所有 HTML。
尽管如此,正则表达式并不是实现您想要的唯一方法,尤其是不是最好的方法。

简单的答案是:你没有。曾。HTML不是常规语言,因此正则表达式不能解析HTML。 您需要使用存在于php中的HTML解析器作为DOM。

有关正则表达式不适用于 HTML 的原因的更多信息,请阅读此线程。小马。他来了。

如果这真的是全部代码,这应该就足够了

strip_tags($html);