【问题标题】:preg_replace links in text with <a> with some exceptionpreg_replace 用 <a> 替换文本中的链接,但有一些例外
【发布时间】:2014-08-20 17:21:02
【问题描述】:
<?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" 添加到那些包含的文本中。

谁能帮我解决这个问题?

【问题讨论】:

  • 这可能不是一个适合正则表达式的任务——我建议使用标准的字符串方法以及库函数来识别 URL,因为正则表达式会完全正确地做到这一点。

标签: php regex hyperlink href


【解决方案1】:
$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

【讨论】:

    【解决方案2】:

    这将添加目标:

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

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

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

    【讨论】:

      【解决方案3】:

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

      PHP validation/regex for URL

      将所有 URL 设为链接。

      【讨论】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-05-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-15
          相关资源
          最近更新 更多