PHP 将字符串中的 URL 替换为全新的 URL


php replace url in string with totally new url

我目前正在研究一个短网址脚本来与Twitter一起使用。

目前,我正在将我想要的推文文本输入到具有长 url 的文本区域中。到目前为止,我有以下内容可以检测网址:

$regex = "/(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/";
if ( preg_match( $regex, $text, $url ) ) { // $url is now the array of urls
   echo $url[0];
}

输入推文时,它将如下所示:

hi here is our new product, check it out: www.mylongurl.com/this-is-a-very-long-url-and-needs-to-be-shorter

然后,我生成一些随机字符以附加到新 url 的末尾,因此它最终会如下所示:shorturl.com/ghs7sj。

单击时,shorturl.com/ghs7sj 它会将您重定向到 www.mylongurl.com/this-is-aver-long-url-and-needs-to-be-shorter。这一切都很好用。

我的问题是推文文本仍然包含长网址。有没有办法用短网址替换长网址?我需要一些新代码吗?或者我可以调整上述内容来做到这一点吗?

我想要的结果是这样的:

 hi here is our new product, check it out: shorturl.com/ghs7sj

这是基于wordpress的,因此所有信息目前都存储在帖子和post_meta表中。请注意,推文中将只有 1 个网址。

你能只使用 PHP 的 str_replace() 函数吗?类似的东西

str_replace($url, $short_url, $text);

您可以使用 preg_replace_callback() 在回调函数中进行替换:

$regex = "/(http|https|ftp|ftps)':'/'/[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}('/'S*)?/";
$text = preg_replace_callback($regex, function($url) { 
    // do stuff with $url[0] here
    return make_short_url($url[0]);
}, $text);