将模式字符串替换为结构化字符串

时间:2013-09-12 10:12:17

标签: php regex string replace preg-replace

我有一个字符串:

juices vegetables including {{smartpro=img:hippo-1.jpg,alt:abc,ht:217,wd:247,align:left}} wheatgrass, leafy greens, parsley, aloe vera & other herbs


现在这里{{smartpro=img:hippo-1.jpg,alt:abc,ht:217,wd:247,align:left}}
替换为<img src="www.abc.com/media/images/hippo-1.jpg" alt="" width="247" height="217" align="left">所以最后的字符串将是:

juices vegetables including <img src="www.abc.com/media/images/hippo-1.jpg" alt="abc" width="247" height="217" align="left"> wheatgrass, leafy greens, parsley, aloe vera & other herbs

请帮助。
我的尝试:preg_replace('~\{{\{{(.+)\:(.+)\}}\}}~iUs','<img src="$2">$1/>',$string);

2 个答案:

答案 0 :(得分:1)

$string = 'juices vegetables including {{smartpro=img:hippo-1.jpg,alt:Hippocrates,ht:217,wd:247,align:left}} wheatgrass, leafy greens, parsley, aloe vera & other herbs';
$pattern = '/(?:{{smartpro=img:)([^,]+)(?:,alt:)([^,]+)(?:,ht:)([^,]+)(?:,wd:)([^,]+)(?:,align:)([^}]+)(?:}})/i';
$replacement = '<img src="$1" alt="$2" height="$3px" width="$4px" align="$5"/>';
echo preg_replace($pattern, $replacement, $string);

答案 1 :(得分:1)

我不确定为什么你的正则表达式中有\{{\{{。你的字符串中可能有{{{{吗?

此外,(.+):将匹配所有内容,直到最后:,因为.+贪婪。

如果你的字符串总是以相同的顺序,我建议使用它:

{{[^}]*?(?:,?img:([^,}]+))?(?:,?alt:([^,}]+),)?(?:,?ht:(\d+))?(?:,?wd:(\d+))?(?:,?align:(\w+))?}}

并替换为:

<img src="www.abc.com/media/images/$1" alt="$2" width="$3" height="$4" align="$5">

如果缺少一个或多个参数,此正则表达式也将起作用。

regex101 demo