tags:

views:

52

answers:

3
function all_images(&$post){
$content = $post->post_content;
if(preg_match_all('/<img[^>]+src="(.*?)"[^>]*>/', $content, $results)){
 $i = 0;
 $count = count($results);
 $count = $count - 1;
 while($i < $count)
 {
  foreach($results as $result){
   echo $result[$i];
  }
  $i++;
 }
  }
}

The above loop manages to get all of the images out of the original text. However, it only returns one image. I have tried several different combinations of while() and foreach() but it only ever returns one image. Does anyone know what i am doing wrong? Thanks

+4  A: 

$results[1] should be an array of all the matches on the first parenthesized subpattern, so something as simple as this should work:

if(preg_match_all('/<img[^>]+src="(.*?)"[^>]*>/i', $content, $results)){
    foreach($results[1] as $src)
    {
       echo "src is $src<br>";
    }        
}

Note I've used the /i modifier to make the match case insensitive, which might help you.

You might also want to supply some sample content you are trying to match against.

Paul Dixon
Thanks dude! Works superbly.
Drew
+1  A: 

Why are you doing $count = $count - 1?

You should be able to just do this:

if(preg_match_all('/<img[^>]+src="(.*?)"[^>]*>/', $content, $results)){
    foreach($results[1] as $result)
    {
        echo $result;
    }
  }
}
Yuliy
+1  A: 

You have to consider the structure of the array returned by preg_match_all. So try this:

function all_images(&$post)
{
    $content = $post->post_content;
    if (preg_match_all('/<img[^>]+src="(.*?)"[^>]*>/', $content, $results)) {
     // $results[0] contains the whole match of the regular expression
     foreach ($results[0] as $result) {
      echo $result;
     }
    }
}
Gumbo