简体   繁体   中英

Retrieve The link value form <a href> tag using php

I need to extract the link value which is stored in a <a href> tag by using php code.

<a href="http://stackoverflow.com/questions/ask"></a>

From the above code i want to extract the link http://stackoverflow.com/questions/ask using php code.

There are a variety of options..

  • If you know the href will always be the one and only attribute on the a tag, you can find the position of the first and last double quotes using strpos/stripos and use substr to pull out the href.
  • Alternatively, even if there are multiple attributes, strpos/stripos both accept offsets on where to begin the search for you string. If you start after the href, you could do the same as above.
  • Alternatively, you might be better with a regular expression that also finds the href and goes from there.
  • Finally, if this is part of a properly formed XHTML document that you're iterating over, you could use SimpleXML to iterate over the arrays and get each attribute you need.

From the limited information provided, I would start with the first or second options and only go to a regular expression or SimpleXML if there were additional requirements in the mix.

If you already have the anchor tag and just want to get the href value, try this code. It will remove other except the 'href' value. The only problem is the word 'href' can't be inside id/class infront of 'href' attribute.

$url = '<a href="http://stackoverflow.com/questions/ask"></a>';
$url =  substr ( $url,(strpos($url,' href=') + 6) );
$url = explode($url[0],$url);
echo $url[1]; // $url[1] will store the 'http://stackoverflow.com/questions/ask'
$url = '<a title="Question" href="http://stackoverflow.com/questions/ask"></a>'; preg_match("/href=\"(.*?)\"/i", $url, $matches); print_r($matches); /* Match Group(s) : 1. http://stackoverflow.com/questions/ask */

You can't do that unless the link is generated by your PHP code itself. PHP is server side code whereas the link is on the page itself is in HTML client code. The two can't communicate with each other. To extract the value you would need to use a client side script like JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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