In php, how to use pre-replacement to turn url into tinyurl

I need to convert a line of text containing a long url to the same line, but with tinyurl (using tinyurl api). eg. convert

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

at

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

How can I do that?

+3
source share
2 answers

To reduce the number of URLs in the text, put the API stuff in a function that takes a long URL and returns a short URL. Then apply this function using the PHP function preg_replace_callbackto your text. It will look something like this:

<?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

+3

, 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);
0

Source: https://habr.com/ru/post/1736711/


All Articles