在字符串中查找HTML标记

时间:2013-09-14 10:32:36

标签: php html regex preg-match

我知道这个问题是关于SO的,但我找不到合适的问题,而且我还在吸食Regex:/

我有一个string,该字符串是有效的HTML。现在,我想查找具有特定nameattribute的所有标记。

我试过这个正则表达式(即div类型):/(<div type="my_special_type" src="(.*?)<\/div>)/

示例字符串:

<div>Do not match me</div>
<div type="special_type" src="bla"> match me</div>
<a>not me</a>
<div src="blaw" type="special_type" > match me too</div>

如果我使用preg_match,那么我只得到<div type="special_type" src="bla"> match me</div>什么是逻辑的,因为另一个具有不同顺序的属性。

在示例字符串上使用array时,我需要什么正则表达式来获取以下preg_match?:

array(0 => '<div type="special_type" src="bla"> match me</div>',
      1 => '<div src="blaw" type="special_type" > match me too</div>')

2 个答案:

答案 0 :(得分:7)

一般建议:不要使用正则表达式解析HTML 如果HTML发生变化,它会变得混乱。

改为使用DOMDocument

$str = <<<EOF
<div>Do not match me</div>
<div type="special_type" src="bla"> match me</div>
<a>not me</a>
<div src="blaw" type="special_type" > match me too</div>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($str);    
$selector = new DOMXPath($doc);

$result = $selector->query('//div[@type="special_type"]');

// loop through all found items
foreach($result as $node) {
    echo $node->getAttribute('src');
}

答案 1 :(得分:5)

正如hek2msql所说,你最好使用DOMDocument

$html = '
<div>Do not match me</div>
<div type="special_type" src="bla"> match me</div>
<a>not me</a>
<div src="blaw" type="special_type" > match me too</div>';

$matches = get_matched($html);


function get_matched($html){
    $matched = array();

    $dom = new DOMDocument();
    @$dom->loadHtml($html);

    $length = $dom->getElementsByTagName('div')->length;

    for($i=0;$i<$length;$i++){
        $type = $dom->getElementsByTagName("div")->item($i)->getAttribute("type");

        if($type != 'special_type')
            continue;

        $matched[] = $dom->getElementsByTagName("div")->item($i)->getAttribute('src');
    // or   $matched[] = $dom->getElementsByTagName("div")->item($i)->nodeValue;

    }

    return $matched;

}