【问题标题】:Regexp php html [duplicate]正则表达式 php html [重复]
【发布时间】:2014-07-07 11:31:56
【问题描述】:

这是我的 html 字符串的一部分。

<span class="price">£ 343</span>
// Some html code
<span class="price" id="old-price-22898">£ 343</span>
</p><p class="special-price">
<span class="price" id="product-price-22898"> £ 274</span> 

我想要的是得到所有的价格。

所以我尝试了这个正则表达式:

<span class=\"price\"(.*)>(.*)<\/span>

这对我来说很有意义,但我只能得到 &lt;span class="price"&gt; 之间的价格,而不是带有 ID 的 &lt;span&gt; 之间的价格。

有什么帮助吗?

【问题讨论】:

标签: php html regex


【解决方案1】:

或者,您也可以将DOMDocumentxpath 一起使用。考虑这个例子:

$html_string = '<span class="price">£ 343</span><span class="price" id="old-price-22898">£ 343</span></p><p class="special-price"><span class="price" id="product-price-22898"> £ 274</span>';
$html_string = mb_convert_encoding($html_string, 'html-entities', 'utf-8'); 
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->substituteEntities = TRUE;
libxml_use_internal_errors(true);
$dom->loadHTML($html_string);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$prices = array();
foreach($xpath->query('//*[@class="price"]') as $price) {
    $prices[] = $price->nodeValue;
}

echo '<pre>';
print_r($prices);

输出:

Array
(
    [0] => £ 343
    [1] => £ 343
    [2] =>  £ 274
)

【讨论】:

  • 奇怪,为什么这个代码在我机器上的磅符号之前打印 Â?我使用的是 Windows 7,php 文件是 utf8 编码。
  • @user4035 我认为这是关于编码的问题,请检查我的修订版
  • 现在可以正常工作了 :)
  • mb_convert_encoding($html_string, 'utf-8', mb_detect_encoding($html_string)) 可以安全地删除 - 如果文件存储在 utf-8 中,它不会做任何事情。
【解决方案2】:

下面的正则表达式将捕获&lt;span class="price"&gt; 中的 ID 和价格 标签和&lt;span&gt; 标签。

<span class=\".*?(?:(id=[^>]*))?>\s*([^<]*)\s*

DEMO

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多