繁体   English   中英

preg_replace与回调不替换?

[英]preg_replace with callback not replacing?

我具有此功能,以将文本替换为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我的链接在哪里,返回值是hi from

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

如注释中所述,回调函数必须返回一个值,以使其完全起作用。 要将内容绑定在一起,您只需要在回调的末尾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上检查结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM