我只想查找和替换数组键中的单词。我尝试使用正则表达式来做到这一点,但只有部分成功。
例如:
$str = '[something][userName][userEmail][something]';
$user = array(
'id' => (string) '2',
'userName' => (string) 'super user',
'userEmail' => (string) 'superuser@some.domain',
);
// 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);
此代码产生:
[某事][超级用户][superuser@some.domain][某事]
我想要做的是摆脱'超级用户'和'superuser@some.domain'周围的方括号,而不是[something]周围的方括号(在字符串的开头和结尾)
请帮忙。问候