0

配列キーにある単語のみを検索して置換したい。私は正規表現でこれをやろうとしましたが、部分的な成功しかありません。

例えば:

$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.ドメイン」を囲む角括弧を取り除くためにやりたいことはありますが、[何か]を囲む角括弧は取り除きません(文字列の最初と最後)

助けてください。よろしく

4

1 に答える 1

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);
于 2012-10-02T11:45:43.343 に答える