2012-03-02 61 views
0

我試圖讓在這個標籤所需的內容:如何使用preg match獲取此html標記的內容?

<p class="address"> 
desired content 
</p> 

這是我的嘗試:

preg_match_all("/\<p class=\"address\">(.*)\<\/p\>/", $contents, $matches); 

但是$匹配的數組爲空。請幫忙。

感謝

+1

[xpath的](http://schlitt.info/opensource/blog/0704_xpath.html)[替代:(https://gist.github.com/ 1358174)'xpath_match_all('// p [@ class =「address」]',$ html);' – Gordon 2012-03-02 10:17:22

回答

0

你可以試試這個:

$contents = '<p class="address">desired content</p>'; 
$res = preg_match_all("/\<p class=\"address\">(.*)\<\/p\>/s", $contents, $matches); 
var_dump($res); 
var_dump($matches); 

$匹配是不是空的,對不對?

+0

仍然爲空...... – 2012-03-02 09:47:42

+0

你錯過了換行符。 – rodneyrehm 2012-03-02 09:48:59

+0

試試這樣:$ res = preg_match_all(「/ \

(。*)\ <\/p\>/s」,$ contents,$ matches); – Oleg 2012-03-02 09:55:18

0
  1. 您需要設置PCRE_DOTALL標誌,使.也匹配\n - 見modifiers
  2. 使用.*?(ungreedy運營商),以不妨礙捕獲組匹配</p>
  3. 你可以使用不同的模式定界符和單引號刪除所有反斜槓,使您的模式更具可讀性!

像這樣:

<?php 
$contents = '<p class="address"> 
desired content 
</p>'; 
$res = preg_match_all('#<p class="address">(.*?)</p>#s', $contents, $matches); 
var_dump($matches);