PHP str_replace在输出缓冲区上两次

时间:2016-09-12 13:00:26

标签: php output buffer

我想在输出缓冲区上执行几个正则表达式,但是下面的代码没有创建所需的效果。我想首先执行正则表达式来替换" {{"和"}}""哪个工作正常,但后来我想立即缩小HTML输出。

这是我到目前为止所得到的:

<?php
ob_start(function($buffer) {
    $viewfile = join(DIRECTORY_SEPARATOR, array(VIEWS_ROOT, basename(pathinfo(__FILE__)['filename'] . "phtml")));

    if (file_exists($viewfile)) {
        $body = file_get_contents($viewfile);
    } else {
        $body = file_get_contents(join(DIRECTORY_SEPARATOR, array(VIEWS_ROOT, basename("index.phtml"))));
    }

    preg_replace(array("/\>[^\S ]+/s", "/[^\S ]+\</s", "/(\s)+/s"), array(">", "<", "\\1"), ob_get_contents());

    return (str_replace(array("{{title}}", "{{body}}", "/\>[^\S ]+/s", "/[^\S ]+\</s", "/(\s)+/s"), array("Project", $body, ">", "<", "\\1"), $buffer));
});

require_once(join(DIRECTORY_SEPARATOR, array(LAYOUTS_ROOT, "layout.phtml")));

ob_end_flush();
?>

输出是以下文件的合并:

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{title}}</title>
    <link href="css/cosmo.min.css" rel="stylesheet">
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
        <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
    {{body}}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>

使用:

<h1>Hello, World</h1>

我想要以下输出:

<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Project</title><link href="css/cosmo.min.css" rel="stylesheet"><!--[if lt IE 9]><script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script><script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script><![endif]--></head><body><h1>Hello, Julian</h1><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script><script src="js/bootstrap.min.js"></script></body></html>

1 个答案:

答案 0 :(得分:0)

为了获得所需的输出,我用以下内容替换了上面的return语句:

return (preg_replace(array("/\>[^\S]+/s", "/[^\S]+\</s", "/(\s)+/s"), array(">", "<", "\\1"), str_replace(array("{{title}}", "{{body}}"), array("Project", $body), $buffer)));