I want to find and replace only words which are in array keys. I try to do this with regex but only with partial succes.
For example:
$str = '[something][userName][userEmail][something]';
$user = array(
'id' => (string) '2',
'userName' => (string) 'super user',
'userEmail' => (string) '[email protected]',
);
// get the keys.
$keys = array_keys($user);
// get the values.
$values = array_values($user);
// surround each key in word boundary and regex delimiter
// also escape any regex metachar in the key
foreach($keys as &$key) {
$key = '/\b'.preg_quote($key).'\b/';
}
// do the replacement using preg_replace
echo preg_replace($keys,$values,$str);
This code produces:
[something][super user][[email protected]][something]
What I want to do to get rid the square brackets surrounding the 'super user' and '[email protected]' but not those surrounding [something] (at the start and finish of the string)
Please help. Regards