繁体   English   中英

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

[英]find and replace all occurrences of string [php shortcodes]

我正在使用此代码用包含图像的链接替换 ​​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”只是数字。 那么如何遍历所有短代码以将它们替换为链接而不是第一个短代码

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

//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 和/或你的桌子。 这应该可以替代你上面的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM