2009-03-03 11 views
0
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++; 
    } 
    } 
} 

上記のループは、すべてのイメージを元のテキストから取り除くために管理します。ただし、1つの画像しか返しません。 while()とforeach()のいくつかの異なる組み合わせを試しましたが、1つの画像しか返しません。誰かが私が間違っていることを知っていますか?おかげイメージループは1つのイメージを返すだけですが、すべて返すべきです

+0

は配列の配列であるはずですか? –

答えて

4

$結果は、[1]最初の括弧で囲まれたサブパターン上のすべてのマッチの配列でなければなりませんので、このような単純なものは動作するはずです:

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

注Iは、I /修飾子を使用しました大文字小文字を区別しないようにしてください。

また、照合しようとしているサンプルコンテンツを提供することもできます。

+0

ありがとう!すばらしい作品。 – Drew

1

なぜ$ count = $ count-1ですか?

あなたはこれを行うことができるようになります。

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

あなたはpreg_match_allによって返される配列の構造を考慮する必要があります。したがって、これを試してみてください:

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; 
     } 
    } 
} 
関連する問題