0

I am just trying to make it so that {string} will turn into the value of the $string variable.

For example, consider I have the following variables:

$car = 'Audi';
$speed = 'Fast';
$sentence = "The {car} goes {speed}";

I want this to output: The Audi goes Fast

Here is my code which is not working:

$setting['leads_low_subject'] = '{dealer_name} has {leads_left} leads left!';
$dealer_name = 'My Test Dealer';
$leads_left = 6;

$subject = preg_replace('/\{([a-z]+)\}/e', "$$1", $setting['leads_low_subject']);

echo $setting['leads_low_subject'].'<br />';
echo "$subject";

This is echoing:

{dealer_name} has {leads_left} leads left!
{dealer_name} has {leads_left} leads left!

When it should be echoing:

{dealer_name} has {leads_left} leads left!
My Test Dealer has 6 leads left!

Why is it not working properly?

4
  • 1
    {dealer_name} has an underscore, but you match [a-z]+, might try with [a-z_]+ or \w+ where \w is a shorthand to [A-Za-z0-9_] Commented Mar 5, 2014 at 22:08
  • str_replace would be a much better idea Commented Mar 5, 2014 at 22:08
  • 1
    i knew it was something rediculously simple. thank you jonny. dagon, im aware of the security flaws, but the $setting variable content is not publicly accessible and will never contain a malicious string. Commented Mar 5, 2014 at 22:09
  • @scarhand the e modifier is deprecated. Use preg_replace_callback() as a replacement. Commented Mar 5, 2014 at 22:21

2 Answers 2

4

The fastest way i see is to use strtr():

$trans = array( '{car}'   => 'Audi',
                '{speed}' => 'Fast');

$result = strtr($sentence, $trans);
Sign up to request clarification or add additional context in comments.

Comments

2

Seems like you are looking for a poor man's template engine. You could use preg_replace_callback():

$tpl_vars = array(
    'car' => 'Ford',
    'speed' => 'fast'
);


$tpl = 'The {car} goes {speed}';

echo preg_replace_callback('/\{(.*?)\}/', function($match) use ($tpl_vars) {
    return $tpl_vars[$match[1]];
}, $tpl);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.