PHP replace string between curly brackets with arr

2019-03-02 02:59发布

问题:

I've a body of content that is read in and it contains numerous strings like {{some_text}} and what I'm trying to do is to find all these occurances and replace them with another value from an array for example $text["some_text"].

I've tried using preg_replace but not sure how I go about taking the found text between the brackets and use it in the replace value.

$body = "This is a body of {{some_text}} text from a book.";
$text["some_text"] = "really cool";
$parsedBody = preg_replace("\[{].*[}]/U", $text[""], $body);

As you can see I'm trying to get the some_texttext out of the string and use it to call an element from an array, this example is very basic as there $bodyvalue is vastly larger and $texthas a couple hundred elements too it.

回答1:

You can use preg_replace_callback and use the capturing group ([^}]+) to find an index in the array $text:

$repl = preg_replace_callback('/{{([^}]+)}}/', function ($m) use ($text) {
            return $text[$m[1]]; }, $body);
//=> This is a body of really cool text from a book.

The use ($text) statement passes the reference of $text to the anonymous function.



回答2:

How about doing it the other way around - instead of finding all {{...}} placeholders and looking up their values, iterate through all values and replace placeholders that match like this:

foreach ($text as $key => $value) {
    $placeholder = sprintf('{{%s}}', $key);
    $body        = str_replace($placeholder, $value, $body);
}

You can even wrap it into a function:

function populatePlaceholders($body, array $vars)
{
    foreach ($vars as $key => $value) {
        $placeholder = sprintf('{{%s}}', $key);
        $body        = str_replace($placeholder, $value, $body);
    }

    return $body;
}


回答3:

Just for fun, using your array as is:

$result = str_replace(array_map(function($v){return '{{'.$v.'}}';}, array_keys($text)),
                      $text, $body);

Or if your array is like $text['{{some_text}}'] then simply:

$result = str_replace(array_keys($text), $text, $body);