2012-03-02 60 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);