1

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 php.

Community
  • 1
  • 1
Shazia
  • 25
  • 2
  • 6

3 Answers3

4
$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

genesis
  • 50,477
  • 20
  • 96
  • 125
  • i have already tried it but it just gives me the anchor ttext..how will i get href โ€“ Shazia Sep 16 '11 at 11:44
  • A lot of people whine about using regex for HTML and, in general, they're right to do so. However, if you _know_ that `$link` is _always_ going to be formatted the same way, then I don't see a problem personally. Just my 2ยข. :) โ€“ Herbert Sep 16 '11 at 11:56
2
<?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";
}
Artefacto
  • 96,375
  • 17
  • 202
  • 225
0

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.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836