preg_replace文本中的链接与< a>有一些例外 [英] preg_replace links in text with <a> with some exception
本文介绍了preg_replace文本中的链接与< a>有一些例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<?php
// I have a string, something like this:
$string = '
Lorep ipsum <a href="http://www.example.com">example</a> lorem ipsum
lorem ipsum http://www.example.com/index.php?param1=val¶m2=val lorem ipsum
';
// I need to do some magick with preg_replace and get string like this:
$string = '
Lorep ipsum <a href="http://www.example.com" target="_blank">example</a> lorem ipsum
lorem ipsum <a href="http://www.example.com/index.php?param1=val¶m2=val" target="_blank">http://www.example.com/index.php?param1=val¶m2=val</a> lorem ipsum
';
?>
所以基本上,我想链接文本中未包含在< a>< / A>并将target =_ blank添加到那些。
So basicly, I want to linkify URLs in text that are not wrapped in <a></a> and add target="_blank" to those that are.
任何人都可以帮我这个吗?
Can anyone help me with this?
推荐答案
$string = preg_replace("/<a(.*?)>/", "<a$1 target=\"_blank\">", $string);
这将增加一个额外的 target = \_blank \
如果已经设置了。
this will add an extra target=\"_blank\"
incase it is already set.
$string = preg_replace("/<a (href=".*?").*?>/", "<a $1 target="_blank">", $string);
这将确保只有一个 target =_ blank$在网址中添加了c $ c>
示例: - http://www.phpliveregex.com/p/6qG
这篇关于preg_replace文本中的链接与< a>有一些例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文