我目前有以下代码,可将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比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>
答案 0 :(得分:4)
<?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;
答案 1 :(得分:0)
您可以使用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>"
答案 2 :(得分:0)
您不需要使用preg_match()
,explode()
和implode()
。只需使用preg_replace()
。您需要对整个网址使用组匹配,以将其替换为<a></a>
$testUrl = "@((https?|ftps?)://([\w\-.]+\.[a-zA-Z]{2,3})(/\S*)?)@";
$newStr = preg_replace($testUrl, "<a href='$1'>$3</a>", $moreOrig);
在demo中查看结果