6

Considering an array of strings:

$array = ('hello', 'hello1', 'hello2');

I need to preg_quote($value,'/'); each of the values.

I want to avoid using foreach. Array walk doesn't work because it passes the key too.

array_walk($array,'preg_quote','/'); //> Errors, third parameter given to preg_quote

Any alternative?

2
  • May I ask, why you don't want to use foreach? Commented Nov 8, 2011 at 14:28
  • 1
    Use array_map(); php.net/array-map Commented Nov 8, 2011 at 14:29

5 Answers 5

24

Try array_map() [doc] with an anonymous function (>= 5.3):

$array = array_map(function($value){
    return preg_quote($value, '/');
}, $array);

Working demo

Sign up to request clarification or add additional context in comments.

4 Comments

Ok at this point it's better a simple foreach imo. More clear. thanks tho will accept soon
@yes123 yes, I'd use foreach, too.
Why not $array = array_map('preg_quote', $array, array('/'));? Edit: never mind, the fact that this worked for me is a fluke of not having a / to escape. The second array is just being ignored.
If you use array_map('preg_quote', $array) and would like to pass third argument as preg_quote() delimiter, you have to have the same amount of 2nd and 3rd parameter on array_map(). Example: array_map('preg_quote', ['/a', '/b', '/c'], ['/', '/', '/']). So, use the code in answer is the best in this case.
3

Use array_map()

$newarray = array_map(function($a) {return preg_quote($a, '/');}, $input_array);

Comments

2

You can do (with PHP 5.3):

array_map(function($elem) { return preg_quote($elem, '/'); }, $array);

In PHP <5.2 there are no annoymous functions (first argument of array map) and in that case you should make a global function.

Comments

1

Use foreach. It's made for that reason. But if you insist:

array_walk($arr, create_function('&$val', '$val = preg_quote($val, "/");'));

3 Comments

@genesis Issues aside, how is this any more "complicated" (I'd use convoluted) than your own? The fact that it is on one line?
@Mr.Disappointment I'm not sure, it just smells more messy for me
The better solution is with callback. Unless you use older then 5.3 php.
0

The alternative we forgot to mention is:

function user_preg_quote($key, $value) {
   return preg_quote($value, '/');
}

array_walk($array, 'user_preg_quote'); 

But still a simple foreach would be better maybe.

Comments

Your Answer

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