Useful Snippets

Welcome!


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

RSS Latest posts from my personal blog


Most viewed posts


Subscribe to RSS feed


Replacing and resolving variables inside a PHP string

Stanislav KhromovStanislav Khromov

If you had a string that looked something like this:

Hello! My name is {$name}, I am {$age} years old.

…and you needed to replace all those variables with something dynamic. Here’s how you can do it:

Alternative 1: Pre-defined array

We can pre-define a replacement array of what we want to exchange and what we want to change things into.

$string = 'Hello! My name is {$name}, I am {$age} years old.';
$replacement_array = array(
    'name' => 'Bob',
    'age' => 22
);

$string_processed = preg_replace_callback(
    '~\{\$(.*?)\}~si',
    function($match) use ($replacement_array)
    {
        return str_replace($match[0], isset($replacement_array[$match[1]]) ? $replacement_array[$match[1]] : $match[0], $match[0]);
    },
    $string);

echo $string_processed;

This script will print:

Hello! My name is Bob, I am 22 years old.

Of course the $replacement_array can contain any values you want, even dynamic ones. But perhaps a pre-defined array is too much work, let’s try another approach:

Alternative 2: Resolve the variables from global space (or whatever scope you happen to be in at the time of execution).

$string = 'Hello! My name is {$name}, I am {$age} years old.';
$name = "Bob";
$age = 22;

$string_processed = preg_replace_callback(
    '~\{\$(.*?)\}~si',
    function($match) use ($name, $age)
    {
        return eval('return $' . $match[1] . ';');
    },
    $string);

echo $string_processed;

No more replacement array! But because we use preg_replace_callback with an anonymous function, we have to declare that we are going to “use” the variables $name and $age inside the callback function.

In effect, this is kind of like a tiny templating engine. :)

Source of regular expression

PHP

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 1
  • Ramy
    Posted on

    Ramy Ramy

    Reply Author

    It is easy, just write the following:

    $html = file_get_contents(‘0.txt’);
    // or user is:
    $html = ‘<html><body>$DATA</body></html>’;
    // remember us single quotation (‘) not double quotation (") for a string
    $DATA = "<h1>Hi</h1>";
    eval("\$html = \"$html\";");
    echo $html;