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

橙三吉。 提交于 2019-12-24 06:52:56

问题


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.


回答1:


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.




回答2:


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'



回答3:


$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
*/



回答4:


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.



来源:https://stackoverflow.com/questions/14036699/retrieve-the-link-value-form-a-href-tag-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!