开发者

how can i extract href from <a> tag using php [duplicate]

开发者 https://www.devze.com 2023-04-05 03:14 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Grabbing the href attribute of an A element
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Grabbing the href attribute of an A element

Given link

$link="<a href='test.php'>test</a>";

How can i separate href and anchor text using p开发者_如何学JAVAhp.


$link = "<a href='test.php'>test</a>";
preg_match('~<a .*?href=[\'"]+(.*?)[\'"]+.*?>(.*?)</a>~ims', $link, $result);
//result[1] == test.php
//result[2] == test

or better one, if you want "test"

$link = "<a href='test.php'>test</a>";
$result = strip_tags($link);

eventually, you can look at DOMDocument


<?php
$link="<a href='test.php'>test</a>";
libxml_use_internal_errors(true);
$dom = new domdocument;
$dom->loadHTML($link);
foreach ($dom->getElementsByTagName("a") as $a) {
    echo $a->textContent, "\n";
    echo $a->getAttribute("href"), "\n";
}


You're not specifically concrete about the string you'd like to parse, but a very easy way to do this with PHP is to parse it as a formatted string in your case (Demo):

$link = "<a href='test.php'>test</a>";

$result = sscanf($link, "<a href='%[^']'>%[^<]</a>", $href, $text);

var_dump($result, $href, $text);

However this is not very stable if the format of the link changes, so you should better look for DomDocument which has been already answered.

0

精彩评论

暂无评论...
验证码 换一张
取 消