PHP-替换变量中的所有{string}


PHP - Replace all {strings} from variable

我有这个变量:

$content = "Hello {file1}. Welcome to {file2}. Status: {file3}";

我想用不同的包含文件替换所有{strings}

例如

{file1} = file1.php
{file2} = file2.php
{file3} = file3.php

因此$content的最终输出也包括这些文件。

我该怎么做?

您可以使用preg_replace_callback()来识别占位符,并将其替换为其他内容:

$content = "Hello {file1}. Welcome to {file2}. Status: {file3}";
$replacements = array(
    '{file1}' => 'file1.php',
    '{file2}' => 'file2.php',
    '{file3}' => 'file3.php',
);
$output = preg_replace_callback(
    '/'{.*?'}/',
    function (array $matches) use ($replacements) {
        $item = $matches[0];
        if (isset($replacements[$item])) {
            // simple replacement: replace the key in $replacements with the value
            $item = $replacements[$item];
        }
        return $item;
    },
    $content
);

上面的代码生成字符串"Hello file1.php. Welcome to file2.php. Status: file3.php",这不是您想要的,但它向您展示了前进的道路。

如果您想放置文件file1.php的原始内容,而不是{file1} a.s.o.,那么使用函数file_get_contents()来获得它:

        if (isset($replacements[$item])) {
            // replace with the raw content of the file
            $item = file_get_contents($item);
        }

如果您想要include 'file1.php',那么您需要编写一个小函数来包含该文件并捕获它可能产生的输出:

        if (isset($replacements[$item])) {
            // replace with the content produced by the included file
            $item = includeFile($item);
        }
// ... somewhere after the rest of the code...
function includeFile($file)
{
    ob_start();
    include($file);
    return ob_get_clean();
}

这里的起始delimeter应该是"{",结束delimeter是"}",参数是在数组中收集的文件名变量。

while (true) {
            //Find starting delimiter
            $paramStart = strpos($this->_templateText, $this->_delimiters[0], $index);
            //No more starting delimiters. Copy rest of the message and return
            if ($paramStart === false) {
                $message .= substr($this->_templateText, $index);
                break;
            }
            //Copy portion up to the starting delimiter to message
            $message .= substr($this->_templateText, $index, $paramStart-$index);
            //Find ending delimiter
            $paramEnd = strpos($this->_templateText, $this->_delimiters[1], $paramStart + $startDelimiterLength);
            //No matching ending delimiter
            if ($paramEnd === false) {
                break;
            }
            //Get the portion between delimiters (i.e. parameter name)
            $paramName = substr(
                $this->_templateText,
                $paramStart + $startDelimiterLength,
                $paramEnd - ($paramStart + $startDelimiterLength)
            );
            //Insert parameter into message
            if (isset($parameters[$paramName])) {
                $message .= $parameters[$paramName];
            }
            //Continue from where we left off
            $index = $paramEnd + $endDelimiterLength;
        }