3

長い 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

どうすればそれができますか?

4

2 に答える 2

3

テキスト内の任意の数の URL を短縮するには、長い URL を受け取って短い URL を返す関数に API を入れます。次に、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を参照してください

于 2010-03-12T20:02:25.883 に答える
0

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);
于 2010-03-12T20:29:10.233 に答える