在php中,如何使用preg替换将URL转换为TinyURL [英] in php how do I use preg replace to turn a url into a tinyurl

查看:0
本文介绍了在php中,如何使用preg替换将URL转换为TinyURL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将包含长URL的文本字符串转换为相同的字符串,但带有TinyURL(使用TinyURL API)。例如。转换

blah blah blah http://example.com/news/sport blah blah blah

进入

blah blah blah http://tinyurl.com/yaeocnv blah blah blah

如何做到这一点?

api

为了缩短文本中任意数量的URL,请将推荐答案放在一个函数中,该函数接受长URL并返回短URL。然后通过PHP的preg_replace_callback函数将该函数应用于您的文本。如下所示:

<?php

function shorten_url($matches) {
    // EDIT: the preg function will supply an array with all submatches
    $long_url = $matches[0];

    // API stuff here...
    $url = "http://tinyurl.com/api-create.php?url=$long_url";
    return file_get_contents($url);
}

$text = 'I have a link to http://www.example.com in this string';

$textWithShortURLs = preg_replace_callback('|http://([a-z0-9?./=%#]{1,500})|i', 'shorten_url', $text);
echo $textWithShortURLs;

?>

不要太依赖该模式,只是在没有任何测试的情况下即时编写它,也许其他人可以提供帮助。 请参见http://php.net/preg-replace-callback

这篇关于在php中,如何使用preg替换将URL转换为TinyURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆