Providing that all your images are under the same path, I recommend you leave regular expressions alone (this time), and opt for a much easier explode()
method.
Using the PHP explode()
function you can split a string into an array using a delimiter.
$str = 'http://localhost/test/images/small/ima1.jpg';
$arr = explode('/',$str);
This should give you something like this -
Array
(
[0] => http:
[1] =>
[2] => localhost
[3] => test
[4] => images
[5] => small
[6] => ima1.jpg
)
// remove the protocol specification and the empty element.
// You'll see that the `explode()` function actually removes the slashes
// (including the two at the beginning of the URL in the protocol specification),
// you'll have to return them once you have finished.
array_shift($arr);
array_shift($arr);
Now you are left with -
Array
(
[0] => localhost
[1] => test
[2] => images
[3] => small
[4] => ima1.jpg
)
Providing the URL's are the same for all images, you can simply replace the fourth element ($arr[3]
) with the relevant size and then reassemble your URL using the implode()
function.
array_unshift($arr,'/'); // adds an element to the beginning of an array
array_unshift($arr,'http:');
$finalURL = implode('/',$arr);
Relevant documentation -