Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am having some issues with PHP preg_replace.

I have a url that contains a image-url with numbers added, e.g.:

$url = http://example.com/111.jpg,121,122,123,124,125,126

The numbers at the end are always different.

To seperate the sting, I am using

$parts = explode(",", $url);

To figure out how many numbers there are, I am using:

$numbers = count($parts);

My problem is to replace the end of $url[0] with $parts (starting with parts[1] up to parts[$numbers-1])

Any idea what I need to change??

Here is my code:

for($i=1;$i<=10;$i++) {
   $array[] = preg_replace('/\d+.jpg/',sprintf("%01d.jpg",$i),$url[0]);
}

<img src="<?php echo($array[0]); ?>"/>
<img src="<?php echo($array[1]); ?>"/>
<img src="<?php echo($array[2]); ?>"/>
<img src="<?php echo($array[3]); ?>"/>
<img src="<?php echo($array[4]); ?>"/>
<img src="<?php echo($array[5]); ?>"/>
<img src="<?php echo($array[6]); ?>"/>
<img src="<?php echo($array[7]); ?>"/>
<img src="<?php echo($array[8]); ?>"/>
<img src="<?php echo($array[9]); ?>"/>
share|improve this question
1  
Your question is hard to parse. What is your desired output? – Sander Marechal Jul 11 '11 at 14:58
Looks good. What is the problem? – powtac Jul 11 '11 at 15:01
add comment (requires an account with 50 reputation)

2 Answers

up vote 2 down vote accepted

Try

$array[] = preg_replace('/\d+.jpg/', "{$url[$i]}.jpg"), $url[0]);

This'll pull out the trailing numbers one at a time. Your original version was replacing with your loop counter, which almost surely were NOT going to be the same as the trailing numbers.

Yours is generating

http://example.com/001.jpg
http://example.com/002.jpg
etc...

and you want

http://example.com/121.jpg
http://example.com/122.jpg
etc...
share|improve this answer
thanks, works like a charm – grosseskino Jul 11 '11 at 15:12
add comment (requires an account with 50 reputation)
$url   = 'http://example.com/111.jpg,121,122,123,124,125,126';
$parts = explode(',', $url);
$url   = array_shift($parts);

$parts_count = count($parts);
for($i=0; $i<$parts_count; $i++) {
  $array[] = preg_replace('/\d+.jpg/', sprintf("%d.jpg", $parts[$i]), $url);
}

var_dump($array);

outputs

array(6) {
  [0]=>
  string(26) "http://example.com/121.jpg"
  [1]=>
  string(26) "http://example.com/122.jpg"
  [2]=>
  string(26) "http://example.com/123.jpg"
  [3]=>
  string(26) "http://example.com/124.jpg"
  [4]=>
  string(26) "http://example.com/125.jpg"
  [5]=>
  string(26) "http://example.com/126.jpg"
}
share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.