Skip to content
Advertisement

Replace all urls with minified urls within a string containing mixed content

I have string with links and iam going to extract links into an array as following

$string = "The text you want to filter goes here. http://google.com, https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/";

preg_match_all('#bhttps?://[^,s()<>]+(?:([wd]+)|([^,[:punct:]s]|/))#', $string, $match);

print_r($match[0]);

results

Array ( 
[0] => http://google.com 
[1] => https://www.youtube.com/watch?v=K_m7NEDMrV0 
[2] => https://instagram.com/hellow/ 
) 

Now i will use bit.ly API function gobitly() for link shorten that ends with array like this

foreach ($match[0] as $link){
    $links[] = gobitly($link);
}

the results of $links[]

Array ( 
[0] => http://t.com/1xx
[1] => http://t.com/z112
[2] => http://t.com/3431
) 

Now I want to rebuild the string and replace links to the new one to be like this

$string = "The text you want to filter goes here. http://t.com/1xx, http://t.com/z112,http://t.com/3431";

Advertisement

Answer

Since you know the key of the url to be replaced, you can simply loop over then and use str_replace to replace each shorturl with the original;

<?php

$string = "The text you want to filter goes here. http://google.com, https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/";

preg_match_all('#bhttps?://[^,s()<>]+(?:([wd]+)|([^,[:punct:]s]|/))#', $string, $match);

// Shorten array
$short = [ 'http://t.com/1xx', 'http://t.com/z112', 'http://t.com/3431' ];

// For each url
foreach ($match[0] as $key => $value) {
    
    // Replace in original text
    $string = str_replace($value, $short[$key], $string);
}

echo $string;

The text you want to filter goes here. http://t.com/1xx, http://t.com/z112,http://t.com/3431

Try it online!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement