HTML 模板中多次出现分量表


Multiple occurances of delimeters within a HTML template

我面临着一个我无法解决的问题。我想我会再次求助于专家来照亮一些光芒。

我有一个 HTML 模板,在模板中我有分隔符,例如:

[has_image]<p>The image is <img src="" /></p>[/has_image]

这些分隔符在模板中可能多次出现,以下是我试图实现的目标:

  • 查找这些分隔符的所有匹配项,并将这些分隔符之间的内容替换为图像源,或者如果图像不存在,则将其替换为空,但仍保留其余模板的值/内容。

下面是我的代码,它仅适用于一次出现,但很难为多次出现而努力完成它。

function replace_text_template($template_body, $start_tag, $end_tag, $replacement = ''){
    $occurances = substr_count($template_body, $start_tag);
    $x = 1;
    while($x <= $occurances) {      
        $start = strpos($template_body, $start_tag);
        $stop = strpos($template_body, $end_tag);
        $template_body = substr($template_body, 0, $start) . $start_tag . $replacement . substr($template_body, $stop);     
        $x++;   
    }
    return $template_body;
}
$template_body will have HTML code with delimiters
replace_text_template($template_body, "[has_image]", "[/has_image]");

无论我是否删除 while 循环,它仍然适用于单个分隔符。

我已经设法解决了这个问题。如果有人觉得这很有用,请随时使用该代码。但是,如果有人找到更好的方法,请分享它。

function replace_text_template($template_body, $start_tag, $end_tag, $replacement = ''){
    $occurances = substr_count($template_body, $start_tag);
    $x = 1;
    while($x <= $occurances) {      
        $start = strpos($template_body, $start_tag);
        $stop = strpos($template_body, $end_tag);           
        $template_body = substr($template_body, 0, $start) . $start_tag . $replacement . substr($template_body, $stop);     
        $template_body = str_replace($start_tag.''.$end_tag, '', $template_body); // replace the tags so on next loop the position will be correct
        $x++;   
    }
    return $template_body;
}
function replace_text_template($template_body, $start_tag, $replacement = '') {
    return preg_replace_callback("~'[".preg_quote($start_tag)."'].*?'['/".preg_quote($start_tag)."']~i", function ($matches) use ($replacement) {
        if(preg_match('~<img.*?src="([^"]+)"~i', $matches[0], $match)) {
            if (is_array(getimagesize($match[1]))) return $match[1];
        }
        return $replacement;
    }, $template_body);
}
$template_body = <<<EOL
text
[has_image]<p>The image is <img src="" /></p>[/has_image]
abc [has_image]<p>The image is <img src="http://blog.stackoverflow.com/wp-content/themes/se-company/images/logo.png" /></p>[/has_image]xyz
EOL;
echo replace_text_template($template_body, "has_image", "replacement");

返回:

text
replacement
abc http://blog.stackoverflow.com/wp-content/themes/se-company/images/logo.pngxyz