tags:

views:

311

answers:

2

I need to convert a string of text containing a long url into the same string but with a tinyurl (using the tinyurl api). eg. convert "blah blah blah /http://example.com/news/sport blah blah blah" into "blah blah blah http://tinyurl.com/yaeocnv blah blah blah".

How can it be done? PLEASE NOTE I added a slash before the long url as I'm only allowed to post one link

+3  A: 

In order to shorten an arbitrary number of URLs in your text, put the API stuff in a function which takes the long URL and returns the short URL. Then apply this function via PHP's preg_replace_callback function to your text. This would 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;

?>

Don't count on that pattern too much, just wrote it on-the-fly without any testing, maybe someone else can help. See http://php.net/preg-replace-callback

thanks I tried that but doesn't work (unless I'm using it wrong) Should echo $textWithShortURLs return the string with the short url?
Steven
That's correct. $textWith... contains your whole text with the altered URLs in it. However, there was another mistake in my script which I've just fixed. Actually, the long URL is in $matches[0], $matches[1] just contains the URL without http://.
@the-banana-king: I fixed your regex it has a-b instead of a-z
Erik
@TBK: I also updated your code with the proper bits from mine, and deleted my answer. +1 to you for figuring out what he meant :)
Erik
THANKS! it works perfectly. Just one more question tho...is there a way I can make it so that urls are only shortened if the the string length exceeds 100 characters for example?
Steven
RESOLVED: if (strlen($text)>100){echo $textWithShortURLs;} else {echo $text;}
Steven
PROBLEM: the code only works when urls start with http. How can I recode to also accept urls like www.example.com?
Steven
SOLVED: created a second preg replace for www and put both into a new functi, THANKS AGAIN for all your help.
Steven
A: 

To answer your question of how to do this with preg_replace, you can use the e modifyer.

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