長い 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
どうすればそれができますか?
テキスト内の任意の数の 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を参照してください
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);