Here is yet another way to do this and preserve your spaces:
$my_string = "http://apinmo.com/1/2/3.jpg 4444/8888/7777 http://apinmo.com/4/5/8-1.jpg";
$string_array = explode(' ', $my_string);
print_r($string_array); // for testing
$new_array = '';
foreach($string_array AS $original) {
$pos = strpos($original, 'http');
if(0 === $pos){
$new = preg_replace('/(?<=\d)\/(?=\d)/', '', $original);
$new_array[] = $new;
} else {
$new_array[] = $original;
}
}
$new_string = implode(' ', $new_array);
echo $new_string;
Returns (note the preserved spaces):
http://apinmo.com/123.jpg 4444/8888/7777 http://apinmo.com/458-1.jpg
EDIT - Pure regex method:
$new_string = preg_replace('/(?<=\/\d)(\/)/', '', $my_string);
echo $new_string;
Returns: http://apinmo.com/123.jpg 4444/8888/7777 http://apinmo.com/458-1.jpg
CAVEATS:
a. ) works even if there are no spaces in the string
2. ) does not work if any number between / is more than one digit in length.
iii. ) if the second group of digits is like 4444/5/8888 the second slash would get removed here too.
Here is how the regex breaks down:
Using a positive lookbehind to match a / followed by a digit (?<=\/\d) I can assert what I am looking for - I only want to remove the forward slashes after a forward slash followed by a digit. Therefore I can capture the other forward slashes with (\/) immediately after the lookbehind. There is no need to include http:// to start or .jpg to close out.