簡體   English   中英

PHP preg_match 並替換標簽之間的多個實例

[英]PHP preg_match and replace multiple instances between tags

對不起,如果標題有點混亂,很難解釋,所以我會盡力的:)

好的,我有一個博客,在后端,我希望能夠在帖子中為每個產品添加多個畫廊

示例博客:

Some Product Title 1
blah blah blah blah
[Gallery::product_id_01]

Some Product Title 2
blah blah blah blah
[Gallery::product_id_02]

所以在這個例子中,有 2 個產品,每個產品都有一個 Gallery 標簽。 我希望能夠找到並替換這些示例標簽[Gallery::product_id_01][Gallery::product_id_02]與實際圖片庫,這是通過名為ProdImgGallery()的 php 函數完成的,它傳遞相同的 ID 示例: product_id_01

標簽將始終具有[Gallery::*]但由 * 指示的 :: 之后的文本將有所不同,需要從標簽中捕獲以供下一階段使用。

使用preg_match_all("/\\[Gallery::([^\\]]*)\\]/", $blog_content, $product_id); 找到您期望的所有標簽,但我需要用其唯一 ID 指示的正確圖庫替換標簽

這是我所能得到的,但這只是根據preg_match_all找到的所有 id 獲取每個畫廊我不知道如何用相應的畫廊替換每個畫廊

//Find all Matches and put in array    
preg_match_all("/\[Gallery::([^\]]*)\]/", $blog_content, $product_id);

//Count all matches
$all_matches = count($product_id[1]);

//Loop through them
for($x=0;$x<$all_matches;$x++)
{
echo $product_id[1][$x]."<br>";
$prod_img_gallery = ProdImgGallery($product_id[1][$x]);
}
$blog_content = preg_replace("/\[Gallery::([^\]]*)\]/",$prod_img_gallery,$blog_content);

希望這有點道理,我無法解釋事情,所以請原諒我:) 我也嘗試過搜索,但找不到與我的確切問題相符的答案

非常感謝!

您可以嘗試使用preg_replace_callback

$input = "Some Product Title 1
blah blah blah blah
[Gallery::product_id_01]

Some Product Title 2
blah blah blah blah
[Gallery::product_id_02]";

$out = preg_replace_callback(
    "/\[Gallery::(.*?)\]/", function($m) {
                                $val = "[Gallery::" . ProdImgGallery($m[1]) . "]";
                                return $val;
                            },
    $input);
echo $out;

這里的想法是捕獲[Gallery::...]每次出現,然后將捕獲的組傳遞給回調函數。 上面的腳本使用內聯匿名函數進行回調,然后使用ProdImgGallery()函數返回您想要的替換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM