正则表达式 - 查找具有特定ID的所有元素

时间:2016-01-09 17:51:26

标签: php regex

我想找到所有< * style> HTML中的标签,例如只有一个ID(代码应该只返回带有fixed_id的标签):

<style id="fixed_id" type="text/css">all css code</style>

我有以下代码..

$html = '<style id="fixed_id" type="text/css">css_code</style><style id="ignore_this" type="text/css"></style>';    
preg_match_all("@<style[^>]+(id=['\"fixed_id\"]?)[^>]+(type=['\"]?[^'\"]+['\"]?)?[^>]+?>(.+?)</style>@is", $html, $matches);

我还需要删除所有&lt; * style&gt;具有特定ID的标签,因为我使用以下代码,显然不是选择正确的选择器而是删除所有&lt; * style&gt;标签

$html = preg_replace("/<style\\b[^>]*>(.*?)<\\/style>/s", "", $html);

1 个答案:

答案 0 :(得分:2)

  

注意:为多个标签分配相同的ID在语义上是错误的。一   标签 - 一个ID。

删除所有&lt; * style&gt;带有特定ID的标签:

$html = '<style id="ignore_this" type="text/css"></style><style class="test_class" id="fixed_id" type="text/css">css_code</style><style id="ignore_this" type="text/css"></style>';

$id = "fixed_id"; // could be any other value
$res = preg_replace('/<style(\s+([a-z\-]+)=(\'|\")([^\"\'>]*)(\'|\"))* id="' . $id .'" .*?>.*?<\/style>/i', "", $html);

var_dump($res);
// outputs '<style id="ignore_this" type="text/css"></style><style id="ignore_this" type="text/css"></style>'

要查找&lt; * style&gt;仅包含特定ID的代码:

// I've changed IDs to be unique
$html = '<style id="ignore_this" type="text/css"></style><style class="test_class" id="fixed_id" type="text/css">css_code</style><style id="ignore_this2" type="text/css"></style><style data-id="111" id="fixed_id2" type="text/css">css content</style>';
preg_match_all('/<style(\s+([a-z\-]+)=(\'|\")([^\"\'>]*)(\'|\"))* id="' . $id .'" .*?>(?P<value>.*?)<\/style>/i', $html, $matches);

var_dump($matches['value']);  // using named submask to indicate captured tag value(text)
// outputs value of the captured tag as expected
0 => string 'css_code' 

我还建议您使用DOMDocument来实现这些目标(操纵HTML内容)。它允许您以更精确和更广泛的方式处理HTML内容。

$doc = new \DOMDocument();
$doc->loadHTML($html); // $html from above

$xpath = new \DOMXPath($doc);
$id = "fixed_id"; // could be any other value
foreach ($xpath->query('//style[@id="'.$id.'"]') as $node) {
    echo $node->nodeValue;
}
// outputs 'css_code' as expected  
相关问题