preg_replace与回调不替换?

时间:2019-01-18 16:59:39

标签: php

我具有此功能,以将文本替换为url到url链接。 回调用于检查链接中是否包含http;如果没有,则在其上添加http:

<?php

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];
            $url = '<a href="'.$url.'" target="_blank" 
                       title="'.$url.'">'.$url.'</a>';
        }
    },$titulo);


    return $titulo;
}


echo toLink("hi from www.google.com");

返回值为hi from,我的链接在哪里?

2 个答案:

答案 0 :(得分:1)

您的回调需要返回应插入的字符串(或值)。 This为您提供了更多信息。

答案 1 :(得分:1)

如注释中所述,回调函数必须返回一个值,以使其完全起作用。要将内容绑定在一起,只需在回调的末尾添加一个return $url语句即可,如下所示:

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];
            $url = '<a href="'.$url.'" target="_blank" 
                       title="'.$url.'">'.$url.'</a>';
        }
        return $url;    // <---- return the $url
    },$titulo);


    return $titulo;
}


echo toLink("hi from www.google.com");

检查https://eval.in/1079110上的结果

相关问题