将锚标记替换为括号中的href


Replace anchor tag with href in parenthesis

我想用纯文本中的href部分替换html锚定标记。

所以,

$input = "Please go to <a href='http://www.google.com' style='color:red'>Google</a> or <a href='http://www.yahoo.com' style='color:red'>Yahoo</a> and search.";
echo fixlinks($input);
// "Please go to Google (http://www.google.com) or Yahoo (http://www.yahoo.com) and search."

更新:我可以使用regex来完成,但它也需要适用于输入字符串中的许多url

更新:最终这样做,Elmo的答案如下:

preg_replace("/<a.+href=['|'"]([^'"'']*)['|'"].*>(.+)<'/a>/i",''2 ('1)',$html)

您可以在PHP:中使用Regex

$input_string = "Please go to <a href='http://www.google.com' style='color:red'>Google</a> and search.";
$pattern = "/<a['w's'.]*href='(['w:'-'/'.]*)'['w's'.'=':>]+<'/a>/";
$replacement = '('1)';
$output_string = preg_replace($pattern, $replacement, $input_string);

此正则表达式将整个a标记与其内容和独立的href值相匹配。然后简单的preg_replace函数用匹配的href值替换匹配的a标签。

您可以将所有HTML重写为:

<a href='http://www.google.com'>Google</a> (http://www.google.com)

或者您可以使用javascript自动完成页面中的所有<a>标签:

var theLinks=document.querySelectorAll('a');
for (var x=0; x<theLinks.length; x++){
  theLinks[x].outerHTML+=" ("+theLinks[x].href+")";
}

事实上,我并不完全确定outerHTML的滑稽用法是否有效,但你可以很容易地将其附加到innerHTML中,也可以对URL文本进行超链接,这肯定有效。

这里有一个更通用的版本(这个版本更短更可靠):

preg_replace('/<a.*href=["'']([^"'']*)["''].*>(.*)<'/a>/U', ''2 ('1)', $input);

为什么它更好?

  • 它处理两种类型的引号["'']
  • 它使用([^"'']*)(任何不是报价的东西)来捕获URL,因此它可以处理您提供的任何href
  • 它使用(.*)来捕获链接文本,因此它几乎可以处理您提供的任何链接文本
  • 请注意,它需要U修饰符来使这两个捕获不贪婪

它在这里发挥作用:https://www.phpliveregex.com/p/t9s#tab-preg替换