php正则表达式从数组和方括号替换

时间:2012-10-02 11:39:22

标签: php regex arrays key

我想找到并替换数组键中的单词。我试着用正则表达式做这个,但只是部分成功。

例如:

$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);

此代码生成:

[something] [超级用户] [superuser@some.domain] [某事]

我想做什么来摆脱围绕'超级用户'和'superuser@some.domain'的方括号,而不是围绕[某事]的那些(在字符串的开头和结尾处)

请帮忙。此致

1 个答案:

答案 0 :(得分:1)

为什么不添加方括号来替换模式?

    $str = '[something][userName][userEmail][something]';

    /* ... */
foreach($keys as &$key) {
       $keyWithSquareBrackets = '[' . $key . ']';
       $key = '/\b'.preg_quote($keyWithSquareBrackets).'\b/';
}

// do the replacement using preg_replace                
echo preg_replace($keys,$values,$str);