【问题标题】:in php how do I use preg replace to turn a url into a tinyurl在 php 中,我如何使用 preg replace 将 url 变成 tinyurl
【发布时间】:2011-01-26 23:29:05
【问题描述】:

我需要将包含长 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

怎么做?

【问题讨论】:

    标签: php replace pcre


    【解决方案1】:

    为了缩短文本中任意数量的 URL,请将 API 内容放在一个函数中,该函数接受长 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

    【讨论】:

    • 谢谢,我试过了,但不起作用(除非我用错了) echo $textWithShortURLs 是否应该返回带有短 url 的字符串?
    • 没错。 $textWith... 包含您的整个文本,其中包含更改后的 URL。但是,我刚刚修复了我的脚本中的另一个错误。实际上,长 URL 在 $matches[0] 中,$matches[1] 只是包含没有 http:// 的 URL。
    • @the-banana-king: 我修复了你的正则表达式,它有 a-b 而不是 a-z
    • @TBK:我还用我的正确位更新了您的代码,并删除了我的答案。 +1 给你搞清楚他的意思:)
    • 谢谢!它完美地工作。还有一个问题...有没有一种方法可以使 URL 仅在字符串长度超过 100 个字符时才缩短?
    【解决方案2】:

    要回答您关于如何使用 preg_replace 执行此操作的问题,您可以使用 e 修改器。

    function tinyurlify($href) {
     return file_get_contents("http://tinyurl.com/api-create.php?url=$href");
    }
    $str = preg_replace('/(http:\/\/[^\s]+)/ie', "tinyurlify('$1')", $str);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 2015-12-23
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多