0

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) '[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);

This code produces:

[something][super user][[email protected]][something]

What I want to do to get rid the square brackets surrounding the 'super user' and '[email protected]' but not those surrounding [something] (at the start and finish of the string)

Please help. Regards

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.