0

I have a string, that can has simple templates. And I have an array with values for replacemenet. Currently I am doing it with loop. But I want to change it to preg_replace. Can you help me?

Example:

$values = array(
    'id'   => 120,
    'name' => 'Jim'
);
$string = 'Hello <!name!>. Your ID is <!id!>';
$output = preg_replace(...); // Hello Jim. Your ID is 120

Also preg_replace should work not only with id and name, but with any other keys. Thanks.

1
  • I would probably use preg_replace_callback and a closure. Commented Mar 20, 2012 at 9:34

1 Answer 1

3

Something like the following?

<?php
$values = array(
    'id'   => 120,
    'name' => 'Jim'
);
$string = 'Hello <!name!>. Your ID is <!id!>';

function foo($val) {
        return '/<!' . $val . '!>/';
}

echo preg_replace(array_map('foo', array_keys($values)), array_values($values), $string);

If the whole thing is in a class:

class Template {
        static function bar($val) {
                return '/<!' . $val . '!>/';
        }

        function render($values, $string) {
                echo preg_replace(array_map(array('Template', 'bar'), array_keys($values)), array_values($values), $string);
        }
}

$values = array(
    'id'   => 120,
    'name' => 'Jim'
);
$string = 'Hello <!name!>. Your ID is <!id!>';
$T = new Template();
$T->render($values, $string);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Good thing. Can I use class method instead of function for array_map()?
preg_replace_callback() is an alternative.

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.