简体   繁体   English

<a href>使用php</a>检索链接值表单<a href>标签</a>

[英]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. 我需要使用php代码提取存储在<a href>标记中的链接值。

<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. 从上面的代码中,我想使用php代码提取链接http://stackoverflow.com/questions/ask

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. 如果您知道href始终是标签上的唯一属性,则可以使用strpos / stripos找到第一双引号和最后一个双引号的位置,并使用substr提取href。
  • Alternatively, even if there are multiple attributes, strpos/stripos both accept offsets on where to begin the search for you string. 另外,即使存在多个属性,strpos / stripos都接受从何处开始搜索字符串的偏移量。 If you start after the href, you could do the same as above. 如果您在href之后开始,则可以执行上述操作。
  • Alternatively, you might be better with a regular expression that also finds the href and goes from there. 另外,使用正则表达式也可以找到href并从那里去可能会更好。
  • 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. 最后,如果这是要迭代的格式正确的XHTML文档的一部分,则可以使用SimpleXML迭代数组并获取所需的每个属性。

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. 从提供的有限信息开始,我将从第一个或第二个选项开始,如果混合中还有其他要求,则仅转到正则表达式或SimpleXML。

If you already have the anchor tag and just want to get the href value, try this code. 如果您已经有了anchor标签,并且只想获取href值,请尝试以下代码。 It will remove other except the 'href' value. 它将删除除“ href”值以外的其他值。 The only problem is the word 'href' can't be inside id/class infront of 'href' attribute. 唯一的问题是,“ href”一词不能位于“ href”属性的id / class前面。

$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代码本身生成的,否则您不能这样做。 PHP is server side code whereas the link is on the page itself is in HTML client code. PHP是服务器端代码,而页面上的链接本身是HTML客户端代码。 The two can't communicate with each other. 两者无法相互交流。 To extract the value you would need to use a client side script like JavaScript. 要提取值,您需要使用客户端脚本(例如JavaScript)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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