Regexp php html


Regexp php html

这是我的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> 

我想要的是所有的价格。

所以我试了这个regexp:

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

这对我来说是有意义的,但我只得到<span class="price">之间的价格,而不是<span>之间的价格。

有什么帮助吗

或者,您也可以将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
)

下面的regex将捕获<span class="price">中的id和价格标签和<span>标签

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