preg_replace带有 <a> 的文本链接,但有一些例外


preg_replace links in text with <a> with some exception

<?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&param2=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&param2=val" target="_blank">http://www.example.com/index.php?param1=val&param2=val</a> lorem ipsum
';
?>

所以基本上,我想链接未包装在 中的文本中的 URL,并将 target="_blank" 添加到那些包装中。

谁能帮我解决这个问题?

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

这将添加一个额外的target='"_blank'"以防它已经设置。

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

这将确保在 URL 中仅添加一个target="_blank"

示例:- http://www.phpliveregex.com/p/6qG

这将添加目标:

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

这是一种检测 URL 并将它们制作成链接的粗略方法(这很脆弱):

$string = preg_replace("/(http[^' ]+)/", "<a href='"$1'" target='"_blank'">$1</a>", $string);

首先,我会使用一些XML/HTML处理库来获取标签之间的文本,然后使用简单的正则表达式:

URL 的 PHP 验证/正则表达式

将所有网址设为链接。

$result = preg_replace(
  "/(?<!['>https?:'/'/|href='"'])(?<http>(https?:['/]['/]|www'.)([a-z]|[A-Z]|[0-9]|['/.&?= ]|[~])*)/",
  "<a href='"$1'">$1</a>",
  $string
);