我想在我的网站上添加一些宏,例如。 [产品]牛奶[/产品],当它向用户展示时,我希望它从“牛奶”、图像、产品名称、产品描述中获取一些数据。
编辑
我有 500 多个 [产品] 条目,所有条目都有图像、产品名称、产品描述。如果我写一个食谱,我希望能够通过使用 [product]egg[/product] 和 [product]milk[/product] 添加牛奶和鸡蛋的图像,并且应该将其替换为上面的数据。
我考虑过将所有内容都放在 xml 文件或数组中。
最佳答案
如果您需要一个通用解决方案,允许您替换 [anyTagName]anyContent[/anyTagName],您可以尝试以下代码:
$regex = '/\\[(\\w+)\\](\\w+)\\[\\/\\1\\]/';
$content = 'A string with some [product]milk[/product] tags';
$parsedContent = preg_replace_callback($regex,function ($matches) {
return process_tags($matches[1],$matches[2]);
},$content);
function process_tags($tagName,$tagContent) {
//What you return from this function will replace the [tagName]tagContent[/tagName] tags.
if ($tagName == 'product') {
//This is a product tag, return something based on $tagContent
}
}
关于php - 如何制作现场宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19958192/