grosseskino
grosseskino

Reputation: 299

PHP Change end of value?

I am having some trouble with php.

I have a variable $image that contains a url, like

$image='http://example.com/image.jpg'

I am trying to change the name of the image to this, meanwhile not changing the url:

$image='http://example.com/image01.jpg'
$image='http://example.com/image02.jpg'
$image='http://example.com/image03.jpg'
and so on..

Any idea how I can do this? Or should I use some Javascript?

Upvotes: 0

Views: 83

Answers (2)

Anne
Anne

Reputation: 27073

Code:

$link = 'http://example.com/image.jpg';
for($i=1;$i<=3;$i++) {
    $array[] = str_replace('.jpg',sprintf("%02d",$i).'.jpg',$link);
}
print_r($array);

Result:

Array
(
    [0] => http://example.com/image01.jpg
    [1] => http://example.com/image02.jpg
    [2] => http://example.com/image03.jpg
)

EDIT

This works regardless of extension:

$link = 'http://example.com/image.png';
for($i=1;$i<=3;$i++) {
    $array[] = substr_replace($link,sprintf("%02d",$i),strripos($link,'.'),0);
}
print_r($array);

Result:

Array
(
    [0] => http://example.com/image01.png
    [1] => http://example.com/image02.png
    [2] => http://example.com/image03.png
)

Upvotes: 4

neurino
neurino

Reputation: 12395

This will add numbering before last . whichever is the $image file extension

$image = 'http://example.com/image.jpg';

$pos = strripos($image, '.');
$head = substr($image, 0, $pos);
$tail = substr($image, $pos);

for($i=1; $i<=3; $i++) {
    $image = $head.sprintf("%02d", $i).$tail;
}

Upvotes: 0

Related Questions