简体   繁体   English

<a href>使用php</a>检索<a href>标签的</a>多个值

[英]Retrieve multiple value of a <a href> tag using php

I need to extract the link value which is stored in a <a> tag by using php code. 我需要使用php代码提取存储在<a>标记中的链接值。

I used below code 我用下面的代码

$url = '<a title="Question" href="http://stackoverflow.com/questions/ask">t</a>';
preg_match("/href=\"(.*?)\"/i", $url, $matches);
print_r($matches);

With the above code I can able to get the value of a single href. 使用上面的代码,我可以获取单个href的值。 But it is not working for multiple href in a string(ie $url = '<a title="Question" href="http://stackoverflow.com/questions/ask">t</a><a href="x.php">x</a>';) . 但是它不适用于字符串中的多个href(即$url = '<a title="Question" href="http://stackoverflow.com/questions/ask">t</a><a href="x.php">x</a>';) How can I achieve this? 我该如何实现?

Use preg_match_all() to get all the matches, not just the first. 使用preg_match_all()获取所有匹配项,而不仅仅是第一个。

$url = '<a title="Question" href="http://stackoverflow.com/questions/ask">t</a>&nbsp;<a href="x.php">x</a>';
preg_match_all("/href=\"(.*?)\"/i", $url, $matches);
print_r($matches);

Use a DOM parser, this example should get you going: 使用DOM解析器,此示例将帮助您:

<?php
$doc = new DOMDocument();
$doc->loadHTML('<a title="Question" href="http://stackoverflow.com/questions/ask">t</a>');

$elm = $doc->getElementsByTagName('a')->item(0);

foreach ($elm->attributes as $attr) {
    echo $attr->name . ' ' . $attr->value . '<br>';
}

echo "Directly getting href: " . $elm->attributes->getNamedItem('href')->value;

Output: 输出:

title Question
href http://stackoverflow.com/questions/ask
Directly getting href: http://stackoverflow.com/questions/ask 

Demo: http://viper-7.com/EN1Usi 演示: http : //viper-7.com/EN1Usi

Docs: http://php.net/manual/en/class.domdocument.php 文件: http//php.net/manual/en/class.domdocument.php

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

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