配列キーにある単語のみを検索して置換したい。私は正規表現でこれをやろうとしましたが、部分的な成功しかありません。
例えば:
$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][何か]
「スーパーユーザー」と「スーパーユーザー@some.ドメイン」を囲む角括弧を取り除くためにやりたいことはありますが、[何か]を囲む角括弧は取り除きません(文字列の最初と最後)
助けてください。よろしく