how can i extract href from <a> tag using php [duplicate]
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.
精彩评论