使用 preg_match() 并替换为将 URL 转换为文本中的锚标记

Use preg_match() and replace to converting URL to anchor tag in text

我目前有以下代码可以将 a href 添加到发现 HTTPS:// 的用户提交的纯文本中。问题在于,这显然会将文本中的所有链接更改为相同的 name/location。我怎样才能为文本中的每个 HTTPS:// 实例单独执行此过程?

//Example variables (usually from MySQL)
$moreOrig = "https://duckduckgo.com is better than https://google.com";
// The Regular Expression filter
$testUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

if (preg_match($testUrl, $moreOrig, $url)) {
//split into parts if user has a /something to clean url
    $parts = explode ("/", $url[0]);

    //glue
    list($first, $second, $third) = $parts;

    //output
    $shortUrl = implode ("/", array($third));

    $more = nl2br(preg_replace($testUrl, "<a href='" . $url[0] . "' rel = 'nofollow'>" . $shortUrl . "</a>", $moreOrig));
  }

输出,期望与实际(假设输入变量 =“https://duckduckgo.com?q=Duck+Duck+Go is better than https://google.com?q=Duck+Duck+Go”)

Desired:
<a href = "https://duckduckgo.com?q=Duck+Duck+Go">duckduckgo.com</a> is better than <a href = "https://google.com?q=Duck+Duck+Go">google.com.</a>
<br>
Actual:
<a href = "https://duckduckgo.com?q=Duck+Duck+Go">duckduckgo.com</a> is better than <a href = "https://google.com?q=Duck+Duck+Go">google.com.</a>
<?php declare(strict_types = 1);

$input = "
xxx
https://duckduckgo.com/url/foo
xxx
https://bing.com
xxx
https://google.com/
xxx
";

$result = preg_replace_callback(
    "@
        (?:http|ftp|https)://
        (?:
            (?P<domain>\S+?) (?:/\S+)|
            (?P<domain_only>\S+)
        )
    @sx",
    function($a){
        $link = "<a href='" . $a[0] . "'>";
        $link .= $a["domain"] !== "" ? $a["domain"] : $a["domain_only"];
        $link .= "</a>";
        return $link;
    },
    $input
);

echo $result;

您可以使用 preg_replace_callback 轻松做到这一点。

<?php

//Example variables (usually from MySQL)
$string = "https://duckduckgo.com is better than https://google.com";

// The Regular Expression filter
$pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$result = preg_replace_callback($pattern, function($match) {
    $url = $match[0];
    return sprintf('<a href="%1$s">%1$s</a>', $url);
}, $string);

// Result:
// "<a href="https://duckduckgo.com">https://duckduckgo.com</a> is better than <a href="https://google.com">https://google.com</a>"

您不需要使用 preg_match()explode()implode()。只需使用 preg_replace()。您需要对整个 url 使用分组匹配,以将其替换为 <a></a>

$testUrl = "@((https?|ftps?)://([\w\-.]+\.[a-zA-Z]{2,3})(/\S*)?)@";
$newStr = preg_replace($testUrl, "<a href=''></a>", $moreOrig);

检查结果 demo