Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Placeholder Variables in a String

Tags:

php

preg-match

Just finished making this function. Basically it is suppose to look through a string and try to find any placeholder variables, which would be place between two curly brackets {}. It grabs the value between the curly brackets and uses it to look through an array where it should match the key. Then it replaces the curly bracket variable in the string with the value in the array of the matching key.

It has a few problems though. First is when I var_dump($matches) it puts puts the results in an array, inside an array. So I have to use two foreach() just the reach the correct data.

I also feel like its heavy and I've been looking over it trying to make it better but I'm somewhat stumped. Any optimizations I missed?

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.'
like image 694
Tyler Hughes Avatar asked Apr 02 '13 20:04

Tyler Hughes


People also ask

What is placeholder string?

In computer programming, a placeholder is a character, word, or string of characters that temporarily takes the place of the final data.

How do you put a variable in a placeholder?

To add a placeholder field for a variable In the Placeholder type box, select the variable type you want the placeholder to reference. In the Field properties box, under Variable, type the name for your new variable (or select an existing variable from the drop-down list). For a new variable, click Create Now.

What is a placeholder variable?

Placeholder variables are nontranslatable text strings that stand in for a term or phrase that is used multiple times, or represents a term that shouldn't be translated, such as an official product name.


2 Answers

I think for such a simple task you don't need to use RegEx:

$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.
like image 117
HamZa Avatar answered Oct 21 '22 13:10

HamZa


I hope I'm not too late to join the party — here is how I would do it:

function template_substitution($template, $data)
{
    $placeholders = array_map(function ($placeholder) {
        return strtoupper("{{$placeholder}}");
    }, array_keys($data));

    return strtr($template, array_combine($placeholders, $data));
}

$variables = array(
    'first_name' => 'John',
    'last_name' => 'Smith',
    'status' => 'won',
);

$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you have {STATUS} the competition.';

echo template_substitution($string, $variables);

And, if by any chance you could make your $variables keys to match your placeholders exactly, the solution becomes ridiculously simple:

$variables = array(
    '{FIRST_NAME}' => 'John',
    '{LAST_NAME}' => 'Smith',
    '{STATUS}' => 'won',
);

$string = 'Dear {FIRST_NAME} {LAST_NAME}, we wanted to tell you that you have {STATUS} the competition.';

echo strtr($string, $variables);

(See strtr() in PHP manual.)

Taking in account the nature of the PHP language, I believe that this approach should yield the best performance from all listed in this thread.


EDIT: After revisiting this answer 7 years later, I noticed a potentially dangerous oversight on my side, which was also pointed out by another user. Be sure to give them a pat on the back in the form of an upvote!

If you are interested in what this answer looked like before this edit, check out the revision history

like image 37
antichris Avatar answered Oct 21 '22 15:10

antichris