簡體   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