HTML模板中多次出现分隔符

时间:2015-01-25 13:05:01

标签: php regex substr strpos

我正面临着一个我无法理解的问题。我想我会再次向专家求助,以发光。

我有一个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循环,它仍适用于单个分隔符。

2 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。如果有人发现这个有用,请随意使用该代码。但是,如果有人找到更好的方法,请分享。

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;
}

答案 1 :(得分:0)

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