- preg_replace_callback: documentation ( source)
<?php
$hello = 'Hi';
$name = 'ken';
$replacements = [
'hello' => 'morning',
'invoiceno' => 1234
];
$msg = '$hello, $name (JX02), Your Orders $invoiceno has been delivered. $test $123,99 $123.99 Thank you.';
$result = preg_replace_callback('/\$([\w\_-]{1,})/', function ($match) use ($replacements) {
return array_key_exists($match[1], $replacements) ? $replacements[$match[1]] : (
isset($GLOBALS[$match[1]]) ? $GLOBALS[$match[1]] : '$'.$match[1]
);
}, $msg);
echo $result;