I want to remove parentheses only if they are in the beginning and the end of a given sting :
Example :
$test = array("(hello world)", "hello (world)");
becomes :
$test = array("hello world", "hello (world)");
Try this, using array_map() with an anonymous function, and preg_replace():
$test = array("(hello world)", "hello (world)");
$test = array_map(function($item) {
return preg_replace('/^\((.*)\)$/', '\1', $item);
}, $test);
For example:
php > $test = array("(hello world)", "hello (world)");
php > $test = array_map(function($item) { return preg_replace('/^\((.*)\)$/', '\1', $item); }, $test);
php > var_dump($test);
array(2) {
[0]=>
string(11) "hello world"
[1]=>
string(13) "hello (world)"
}
php >
As @revo pointed out in the comments, we can also modify the array in place to increase performance and reduce memory usage:
array_walk($test, function(&$value) {
$value = preg_replace('/^\((.*)\)$/', '$1', $value);
});
array_map() and storing modified cloned array to the same variable $test, you may use a array_walk() with a pass-by-reference argument.array_walk() as theres no good way to pass the keys by reference.array_map(function($item) use (&$test) { $item = preg_replace(...); }, $test);?array_walk over array_map in your case: array_walk($test, function(&$value) { $value = preg_replace('#^\((.*)\)$#', '$1', $value); });You can use preg_replace with array_map:
$test = array("(hello world)", "hello (world)");
$finalArr = array_map(function($value) {
return preg_replace("/^\((.*)\)$/", "$1", $value);
}, $test);
print_r($finalArr);
Result:
Array
(
[0] => hello world
[1] => hello (world)
)
Remember: It will leave out, (hello world or hello world)
((hello) world), or mismatched(hello) world)))hello() world()etc