解析html时,检查元素是否存在

时间:2013-03-23 20:36:46

标签: php parsing html-parsing

我从一些页面解析html,得到一个传出的列表,我想把它们分成两部分 - 那些有rel =“nofollow”/ rel =“nofollow me”/ rel =“me nofollow”元素和没有那些表达的元素。

目前我正在使用 - PHP Simple HTML DOM Parser

解析下面的代码
$html = file_get_html("$url");

foreach($html->find('a') as $element) {
    echo $element->href; // THE LINK
}    

但我不太确定如何实现它,任何想法?

2 个答案:

答案 0 :(得分:1)

尝试使用以下内容:

$html = file_get_html("$url");

// Creating array for storing links
$arrayLinks = array(
    "nofollow" => array(),
    "others" => array()
);

foreach($html->find('a') as $element) {

    // Search for "nofollow" expression with no case-sensitive (i flag)
    if(preg_match('#nofollow#i', $element->rel)) {
        $arrayLinks["nofollow"][] = $element->href;
    }
    else {
        $arrayLinks["others"][] = $element->href;
    }
} 

// Display the array
echo "<pre>";
print_r($arrayLinks);
echo "</pre>";

答案 1 :(得分:0)

对$ element-&gt; rel进行正则表达式我猜