2012-08-06 79 views
0

可能重複:
How to parse and process HTML with PHP?如何使用preg_match()提取文本?

我有以下存儲在一個變量$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文本。我嘗試了所有可能的解決方案,但沒有成功。

+0

比利是真的。特別是當preg_match不是你需要的函數時,因爲它返回一個布爾值。好像你還沒有嘗試過很多。 – Jerska 2012-08-06 13:48:37

+1

用REGEX解析HTML? s /(?<!拍攝自己在)腳/頭/ g – 2012-08-06 13:49:08

+0

有[strip_tags](http://php.net/strip_tags) – dualed 2012-08-06 13:50:08

回答

1

這應該工作

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

與$包含所有的HTML新。
不過,正則表達式並不是實現你想要的東西的唯一方法,尤其是不是最好的。

+0

嗯,如果這完美的作品,我想知道爲什麼一個簡單的,基於偏移量的字符串搜索,然後是一個子字符串操作並沒有在第一個地方。字符串操作比正則表達式多。 – hakre 2012-08-06 13:58:04

0

如果這是真正的所有代碼,這應該足夠了

strip_tags($html); 
1

簡單的答案是:你不知道。 EVER。 HTML不是正規語言,因此正則表達式CAN NOT PARSE HTML。您需要使用一個HTML解析器,它存在於php中作爲DOM

有關正則表達式不能用於HTML的詳細信息,請參閱this thread。小馬。他來了。

+1

小馬,他厭倦了不斷的來臨。 T͎̹̪̤̤͌ͭ͗ͭ̌̌͊ḧ̆̓ͯ̄͑̑͛͏͖̼͓̤̺ḙ̦͖̥ͩ͠͝r͓̈̈ͯͩ̋ẹ̸͇͕̖̫͖̞̝ͭͨ͌̈̓ͯ͒͘i͇̙̇̉ͩͦ̿̓͆̾ͤ͝s̢̢̻͈͔̺̺͕͕̄̆̽ͬͧͩ͛̉̓ͯͮ̒ͨ͟͡ṉ̡̩͙͇ͬ͌͡o̴̧̖̹͙̥̠̻̬̳̻̻̙̯͛ͣ̋̄̏̑̏̕ȟ͚͙̯̮ͨ͑͟o͓̻͖͙̞͗ͥͫ͝p̢͔͓̫̈̆͋̍ē̛̛͎̜̠̹̯ͧ̊̆͋͢!̧̹̤̞̟͎͖̦ͧ̔ͩ – 2012-08-06 13:57:45