How Can I Efficiently Replace Placeholder Variables in a String?

Susan Sarandon
Release: 2024-11-23 07:05:10
Original
261 people have browsed it

How Can I Efficiently Replace Placeholder Variables in a String?

Optimizing "Replacing Placeholder Variables in a String"

One may encounter various scenarios where identifying and replacing placeholder variables in a string is crucial. This code snippet demonstrates a dynamic replacement function, dynStr, that locates curly bracket ({}) enclosed key-value pairs and updates them accordingly:

function dynStr($str,$vars) {
    preg_match_all("/\{[A-Z0-9_]+\}+/", $str, $matches);
    foreach($matches as $match_group) {
        foreach($match_group as $match) {
            $match = str_replace("}", "", $match);
            $match = str_replace("{", "", $match);
            $match = strtolower($match);
            $allowed = array_keys($vars);
            $match_up = strtoupper($match);
            $str = (in_array($match, $allowed)) ? str_replace("{".$match_up."}", $vars[$match], $str) : str_replace("{".$match_up."}", '', $str);
        }
    }
    return $str;
}

$variables = array("first_name" => "John","last_name" => "Smith","status" => "won");
$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.';
echo dynStr($string,$variables); // Would output: 'Dear John Smith, we wanted to tell you that you won the competition.'
Copy after login

However, as the author highlights, this implementation suffers from redundant array access and appears computationally intensive. One can streamline this process by eliminating the use of regular expressions and implementing a simple string replacement based on the key-value pairs in the "vars" array:

$variables = array("first_name" => "John","last_name" => "Smith","status" => "won");
$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you {STATUS} the competition.';

foreach($variables as $key => $value){
    $string = str_replace('{'.strtoupper($key).'}', $value, $string);
}

echo $string; // Dear John Smith, we wanted to tell you that you won the competition.
Copy after login

This approach removes the unnecessary nested array traversal and streamlines the replacement process, resulting in a cleaner and more efficient code.

The above is the detailed content of How Can I Efficiently Replace Placeholder Variables in a String?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template