简体   繁体   English

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

[英]php regex replace from array and square brackets

I want to find and replace only words which are in array keys. 我只想查找和替换数组键中的单词。 I try to do this with regex but only with partial succes. 我尝试使用正则表达式执行此操作,但只能使用部分成功。

For example: 例如:

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

This code produces: 此代码产生:

[something][super user][superuser@some.domain][something] [某物] [超级用户] [superuser@some.domain] [某物]

What I want to do to get rid the square brackets surrounding the 'super user' and 'superuser@some.domain' but not those surrounding [something] (at the start and finish of the string) 我想做些什么来消除围绕“超级用户”和“ superuser@some.domain”的方括号,而不是围绕[something]的方括号(在字符串的开头和结尾)

Please help. 请帮忙。 Regards 问候

why dont you just add square brackets to replace pattern? 您为什么不添加方括号来替换模式?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM