繁体   English   中英

如何获取href属性的值?

[英]How to get the value of the href attribute?

借助XPath,在以下情况下如何获取href属性的值(仅获取正确的url)?:

<a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>

也就是说,如果链接具有特定文本,则获取href属性的值。

这将选择属性:

"//a[text()='the right one']/@href"

我认为这是最好的解决方案,您可以将它们中的每一个用作数组元素

$String=    '
<a href="http://foo.com">a wrong one</a>
<a href="http://example.com">the right one</a>
<a href="http://boo.com">a wrong one</a>
            ';

$array=get_all_string_between($String,'href="','">');
print_r($array);//just to see what is inside the array

//now get each of them
foreach($array as $value){
echo $value.'<br>';
}

function get_all_string_between($string, $start, $end)
{
    $result = array();
    $string = " ".$string;
    $offset = 0;
    while(true)
    {
        $ini = strpos($string,$start,$offset);
        if ($ini == 0)
            break;
        $ini += strlen($start);
        $len = strpos($string,$end,$ini) - $ini;
        $result[] = substr($string,$ini,$len);
        $offset = $ini+$len;
    }
    return $result;
}
"//a[@href='http://example.com']"

我会使用像simple_html_dom.php这样的开源类

$oHtml = new simple_html_dom();
$oHtml->load($sBody)
foreach($oHtml->find('a') as $oElement) {
    echo $oElement->href
}

这是使用SimpleXML的完整示例:

$xml = '<html><a href="http://foo.com">a wrong one</a>'
        . '<a href="http://example.com">the right one</a>'
        . '<a href="http://boo.com">a wrong one</a></html>';
$tree = simplexml_load_string($xml);
$nodes = $tree->xpath('//a[text()="the right one"]');
$href = (string) $nodes[0]['href'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM