在PHP中替换正则表达式来创建模板


Regex replace to create templating in PHP

我有一个字符串,看起来像这样:

{{imagename.jpg|left|The caption for this image. Includes a variety of chars}}
<p>Some text, lots of paragraphs here.</p>
{{anotherimage.jpg|right|Another caption.}}

我要做的是解析出{{}}位,然后通过一个函数传递它们。目前我得到的是:

function template_function($matches) {
    print_r($matches);
}
function parse_images($string) {
    $string = preg_replace_callback('!'{'{([^}])'}'}!', 'template_function', $string);
    return $string;
}

有人能给我一个手与正则表达式,使我结束了通过print_r运行的匹配?

function template_function($matches) {
    print_r($matches[1]);
}
function parse_images($string) {
    $string = preg_replace_callback('/'{'{([^}]*)'}'}/', 'template_function', $string);
    return $string;
}

也修改了print_r($matches[1]);,使实际匹配打印

您错过了*(或者,可能是+)量词。您的原始表达式将只匹配单个非}字符。

$string = preg_replace_callback('!'{'{([^}]*)'}'}!', 'template_function', $string);