Preg_replace med funktion
Hejsa.Jeg prøver at tage et URL ud af en string og shorte det med google's url shortener API.
Jeg kan dog ikke rigtigt få det til at virke. Selve shortningen er god nok, men jeg er i tvivl om hvor det rent faktisk går galt.
index.php
$pattern = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»""‘']))/";
echo preg_replace($pattern, shortenUrl('$1'), $_POST['message']);
functions.php
function shortenUrl($longUrl){
// Get API key from : http://code.google.com/apis/console/
$apiKey = 'AIzaSyDOqy38W1O0bM_wonW6JJ_uO9_HedW2ZFY';
$postData = array('longUrl' => $longUrl, 'key' => $apiKey);
$jsonData = json_encode($postData);
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url');
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlObj, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
curl_setopt($curlObj, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
curl_setopt($curlObj, CURLOPT_POST, 1);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($curlObj);
// Change the response json string to object
$json = json_decode($response, TRUE);
curl_close($curlObj);
return print_r($json);
}