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

时间:2013-06-09 12:58:06

标签: php foreach preg-replace

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

只是“画廊”bbcode会回应画廊代码。

Everthing没问题,但是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(images)output;

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循环显示一行?

1 个答案:

答案 0 :(得分:1)

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

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