简体   繁体   中英

PHP preg_match and replace multiple instances between tags

Sorry if the title is a little confusing its hard to explain so will try my best :)

Ok I have a blog and in the back end I want to be able to add multiple galleries for each product in a post

Example blog:

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

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

So in this example, there are 2 products each with a Gallery tag. I want to be able to find and replace these example tags [Gallery::product_id_01] and [Gallery::product_id_02] with the actual image gallery, which is done via a php function called ProdImgGallery() this passes the same ID example: product_id_01

The tags will always have [Gallery::*] but the text after the :: indicated by * will be different and needs to be captured from the tag for the next stage.

Using preg_match_all("/\\[Gallery::([^\\]]*)\\]/", $blog_content, $product_id); finds all the tags as you would expect but I then need to replace the tags with the correct gallery indicated by its unique ID

This is as far as I can get but this just fetches each gallery based on all the ids found by preg_match_all I cant figure out how to replace each one with the corresponding gallery

//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);

Hope this makes some kind of sense, I have trouble explaining things so please forgive me :) I did try searching too but could not find an answer that matched my exact problem

Many thanks!

You may try using 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;

The idea here is to capture every occurrence of [Gallery::...] , and than pass the captured group into a callback function. The above script uses an inline anonymous function for the callback, which then returns the replacement you want, using the ProdImgGallery() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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