2012-10-02 90 views
0

我想查找和替換數組鍵中的單詞。我試圖用正則表達式來做到這一點,但只有部分成功。php正則表達式替換數組和方括號

例如:

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

此代碼生成:

[東西] [超級用戶] [[email protected]] [某件事]

我想做什麼就得到什麼清除「超級用戶」和「[email protected]」周圍的方括號,但不包括[something](在字符串的開始和結束處)周圍的方括號

請幫忙。問候

回答

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); 
+0

我試過這個,但是這樣它並不能代替任何東西 – masteryoda