1

I have a text template like this:

$template = [FIRSTNAME] say hello to [NAME]

I have an user array like

[user_name] => myname
[user_firstname] => myfirstname

and I would like to transform it with preg_replace so I tried this:

$replacement = '$user[user_${1}]';
$result['texte'] = preg_replace('/[(.*)]/', {$replacement}, $result['texte']);

without any success :(

2
  • 3
    Have a look at preg_replace_callback() Commented Jun 25, 2013 at 23:27
  • 1
    also, you'll need to escape the square brackets in your regex. otherwise you'll match only one character out of (, ., *, ). Commented Jun 25, 2013 at 23:27

1 Answer 1

5

/[(.*)]/ does not escape the [ or ], and would match essentially everything if it did. Use /\[(.*?)\]/. Additionally, you need to strtolower the matched inner value.

$template = "[FIRSTNAME] say hello to [NAME]";
$replacements = array(
   'user_name' => 'myname',
   'user_firstname' => 'myfirstname',
);

$result['texte'] = preg_replace_callback('/\[(.*?)\]/', function ($match)
    use ($replacements) {
    return $replacements["user_" . strtolower($match[1])];
}, $template)
Sign up to request clarification or add additional context in comments.

1 Comment

Works very well ! Thanks for the tips about regex and []

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.