在文本中使用preg_replace, foreach循环问题


Using preg_replace in text, foreach loop issue

我正在尝试更改文本中的特定单词。

只是"gallery" bbcode's会回显画廊代码。

一切正常,但是foreach循环只返回一行。

这是我的函数

function bbcode_gallery($str){
global $vt,$siteurl;
$thumbheight = "150";
$thumbwidth = "150";
$patterns = "/'[gallery'](.+?)'['/gallery']/i";        
$replacements = "$1";          
$bb_str = preg_replace($patterns, $replacements, $str);  
$gal_id = strip_tags($bb_str);
$gal_id = settype($bb_str, "integer");
$images = $vt->tablo("SELECT * FROM gallery_uploads WHERE gal_id = '$gal_id'");
foreach ($images as $image) {
    $replace = '<img src="'.$siteurl.'/'.$image->url.'" width="'.$thumbwidth.'" height="'.$thumbheight.'">';
}
    //var_dump($images); I specified here is below.
$str = preg_replace($patterns, @$replace, $str); 
echo  $str;
}

var_dump(图像)输出;

Array(
[0] => stdClass Object
    (
        [guid] => 1
        [gal_id] => 1
        [url] => uploads/images/gallery/2bc8e542.jpg
        [type] => gallery
    )
[1] => stdClass Object
    (
        [guid] => 3
        [gal_id] => 1
        [url] => uploads/images/gallery/41ee461a.jpg
        [type] => gallery
    )
[2] => stdClass Object
    (
        [guid] => 4
        [gal_id] => 1
        [url] => uploads/images/gallery/b3768424.jpg
        [type] => gallery
    )
[3] => stdClass Object
    (
        [guid] => 5
        [gal_id] => 1
        [url] => uploads/images/gallery/edb9a830.jpg
        [type] => gallery
    ))

输出;

<p>here is text</p>
<img src="http://site.com/uploads/images/gallery/edb9a830.jpg" width="150" height="150">
<p>here is text</p>

为什么foreach循环只显示一行?

你必须追加而不是替换var $replace -所以它应该是

foreach ($images as $image) {
    $replace .= ''; // dot is require to append to string
}