php 如何在现有的 <a href=""> </a> 上添加 target="_blank"?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15681532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:44:03  来源:igfitidea点击:

How to add target="_blank" on the existing <a href=""> </a>?

phphtmltags

提问by Ray

I have a variable that contains the following text in PhP:

我在 PhP 中有一个包含以下文本的变量:

$description = "Flash <a href=\"http://www.aaa.com/\">this coupon</a> <br > <a href="http://www.ggg.com/">Visit here</a> for details <br >";

How do i add the

我如何添加

target="_blank"

目标=“_blank”

that missing on the $descriptionvariable?

那个缺少$description变量?

So the result will becomes the following:

所以结果会变成下面这样:

$description = "Flash <a href=\"http://www.aaa.com/\" target="_blank">this coupon</a> <br > <a href="http://www.ggg.com/" target="_blank">Visit here</a> for details <br >";

I am looking for solution that the variable $description was recorded by user accidentally. But I need the system to find out and correct it by adding the target="blank" into the existing variable and update the record.

我正在寻找用户意外记录变量 $description 的解决方案。但是我需要系统通过将 target="blank" 添加到现有变量中并更新记录来找出并纠正它。

回答by eL-Prova

I have no idea what your exactly meaning. However, a suggestion to use ' within your HTML. And only " for the echo. So it will be:

我不知道你的确切意思是什么。但是,建议在 HTML 中使用 '。并且只有 " 用于回声。所以它将是:

$description = "Flash <a href='http://www.aaa.com/' target='_blank'>this coupon</a><br ><a href='http://www.ggg.com/' target='_blank'>Visit here</a> for details <br >";

For adding target you can use this:

要添加目标,您可以使用:

$string = preg_replace("/<a(.*?)>/", "<a target=\"_blank\">", $string);

Found on: preg_replace links in text with <a> with some exception

发现于:preg_replace 文本中的链接与 <a> 有一些例外

回答by kero

You already did it, but your code will produce errors since you didn't escape the "in the second link

您已经这样做了,但是您的代码会产生错误,因为您没有"在第二个链接中转义

$description = "Flash <a href=\"http://www.aaa.com/\" target=\"_blank\">this coupon</a> <br > <a href=\"http://www.ggg.com/\" target=\"_blank\">Visit here</a> for details <br >";

Alternatively you can use 'then you don't have to escape

或者你可以使用'然后你不必逃避

$description = 'Flash <a href="http://www.aaa.com/" target="_blank">this coupon</a> <br > <a href="http://www.ggg.com/" target="_blank">Visit here</a> for details <br >';

回答by Narek

$description = str_replace('<a href="','<a target="_blank" href="',$description);

回答by Nick Andriopoulos

If you note that properties of tags do not have a specific order, you can simply replace <a hrefwith <a target=\"_blank\" href

如果你注意到标签的属性没有特定的顺序,你可以简单地替换<a href<a target=\"_blank\" href