Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 文本到链接,没有https的链接有问题_Php_Regex - Fatal编程技术网

Php 文本到链接,没有https的链接有问题

Php 文本到链接,没有https的链接有问题,php,regex,Php,Regex,用户可以添加文本。这些文本可以有链接 我想添加点击到它 问题是,有些链接的工作原理如下: 没有http的链接将无法工作,并将成为: 有什么办法解决吗 function toLink($titulo){ $url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i'; $titulo = preg_replace($url, '<a href="$0" target

用户可以添加文本。这些文本可以有链接

我想添加点击到它

问题是,有些链接的工作原理如下:

没有http的链接将无法工作,并将成为:

有什么办法解决吗

function toLink($titulo){
    $url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i'; 
    $titulo = preg_replace($url, '<a href="$0" target="_blank" title="$0">$0</a>', $titulo);
    return $titulo;
}
函数链接($titulo){

$url='~(?:(https?):/([^\s改用
preg_replace_callback
,您可以查询匹配项以查看是否需要添加协议

function toLink($titulo) {
    $url = '~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i'; 
    $titulo = preg_replace_callback($url, function($matches) {
        $url = $matches[0];
        if (!preg_match('/^https?:\/\//', $url)) $url = 'http://'.$matches[0];
        '<a href="'.$url.'" target="_blank" title="'.$url.'">'.$url.'</a>';
    }, $titulo);
    return $titulo;
}
函数链接($titulo){

$url='~(?:(https?):/([^\s可能重复的@madflow你读过我的问题吗?我想没有。如果你读过,你会注意到我对你标记为重复的相同函数有问题。没有http的链接将不起作用。当我尝试
echo toLink('google.com')时
I get google.com这就是你想要的吗?@MoisheySchwartz试试www.google.com。它将变成www.mywebsite.com/www.google.com。我想在链接前面添加http以避免这种情况。不客气。另外请注意,模式中的大多数子组都是不必要的,因为你在输出中只使用整个匹配项,而不是子组。我正在努力使它工作,但没有成功,我应该把你的代码放在我的toLink函数中吗?请参阅编辑。我现在已经包括了整个编辑过的函数。