php 用全新的 url 替换字符串中的 url

dan*_*nyo 5 php url

我目前正在编写一个简短的 url 脚本来与 twitter 一起工作。

目前我正在将我想要的推文文本输入到一个带有长网址的文本区域中。到目前为止,我有以下检测网址:

$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];
}
Run Code Online (Sandbox Code Playgroud)

当一条推文被输入时,它看起来像这样:

hi here is our new product, check it out: www.mylongurl.com/this-is-a-very-long-url-and-needs-to-be-shorter
Run Code Online (Sandbox Code Playgroud)

然后我生成一些随机字符附加到新 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
Run Code Online (Sandbox Code Playgroud)

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

nat*_*oth 5

你可以只使用 PHP 的str_replace()函数吗?就像是

str_replace($url, $short_url, $text);
Run Code Online (Sandbox Code Playgroud)

  • $url[0] 准确地说。 (2认同)