查找并替换所有出现的字符串[php shortcodes]

时间:2015-11-03 17:29:21

标签: php regex loops str-replace strstr

我正在使用此代码替换CMS中的短代码,其中的链接包括图片,但它只替换了第一个短代码

$string = $row['Content'];
  if(stristr($string,'[gal=')){
    $startTag = "[gal=";
    $endTag = "]";
    $pos1 = strpos($string, $startTag) + strlen($startTag);
    $pos2 = strpos($string, $endTag);
    $gal = substr($string, $pos1, $pos2-$pos1);
    $q=$db->prepare("select * from images where Gal_ID = :gal");
    $q->execute(["gal"=>$gal]);
    $imgs='';
    while($r=$q->fetch(PDO::FETCH_ASSOC)){
        $images[] = $r['Image'];
    }
    foreach($images as $val){
        $imgs .= "<a href='gallery/large/$val' class='fancybox-thumbs' rel='gallery'><img src='gallery/thumb/$val'></a>";
    }
    $result = substr_replace($string, $imgs, $pos1, $pos2-$pos1);
    $result = str_replace($startTag,'',$result);
    $result = str_replace($endTag,'',$result);
    echo $result;
 }
 else{
    echo $string;
 }

字符串包含一些段落和2个短代码

[gal=36] and [gal=37]

结果是仅用链接和图像替换第一个短代码,但第二个短代码显示如下:“37”只是数字。那么如何循环遍历所有短代码以用链接替换它们而不仅仅是第一个短代码

1 个答案:

答案 0 :(得分:1)

这是我上面描述的完整示例。

//get matches
if(preg_match_all('/\[gal=(\d+)\]/i', $string, $matches) > 0){
    //query for all images. You could/should bind this, but since the expression
    //matches only numbers, it is technically not possible to inject anything.
    //However best practices are going to be "always bind".
    $q=$db->prepare("select Gal_ID, Image from images where Gal_ID in (".implode(',', $matches[1]).")");
    $q->execute();

    //format the images into an array
    $images = array();
    while($r=$q->fetch(PDO::FETCH_ASSOC)){
        $images[$r['Gal_ID']][] = "<a href='gallery/large/{$r['Image']}' class='fancybox-thumbs' rel='gallery'><img src='gallery/thumb/{$r['Image']}'></a>";
    }

    //replace shortcode with images
    $result = preg_replace_callback('/\[gal=(\d+)\]/i', function($match) use ($images){
        if(isset($images[$match[1]])){
            return implode('', $images[$match[1]]);
        } else {
            return $match[0];
        }
    }, $string);

    echo $result;
}

我尽可能多地测试它,但我没有PDO和/或你的桌子。这应该可以替代上面的内容。