抱歉,标题有点令人困惑,难以解释,请尽我所能:)
好的,我有一个博客,在后端,我希望能够在一个帖子中为每个产品添加多个画廊
博客示例:
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指示的正确图库替换这些标签
这是我所能获得的,但这只是根据找到的所有ID获取每个图库,preg_match_all
我无法弄清楚如何用对应的图库替换每个图库
//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()
函数返回所需的替换。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句