Php 从数组中删除括号

Php 从数组中删除括号,php,arrays,Php,Arrays,仅当括号位于给定sting的开头和结尾时,我才想删除括号: 例如: $test=array(“(hello world)”,“hello(world)” 变成: $test=array(“你好世界”,“你好(世界)”)您可以使用preg\u replace替换为array\u map: $test = array("(hello world)", "hello (world)"); $finalArr = array_map(function($value) { return preg

仅当括号位于给定sting的开头和结尾时,我才想删除括号:

例如:

$test=array(“(hello world)”,“hello(world)”

变成:


$test=array(“你好世界”,“你好(世界)”)

您可以使用
preg\u replace
替换为
array\u map

$test = array("(hello world)", "hello (world)");

$finalArr = array_map(function($value) {
    return preg_replace("/^\((.*)\)$/", "$1", $value);
}, $test);

print_r($finalArr);
结果:

Array
(
    [0] => hello world
    [1] => hello (world)
)

请记住:它将省略,
(hello world
hello world)

使用,然后尝试以下操作:

例如:

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 >
正如评论中指出的,我们还可以修改阵列以提高性能并减少内存使用:

array_walk($test, function(&$value) {
    $value = preg_replace('/^\((.*)\)$/', '$1', $value);
});
您可以使用正则表达式:

比如说

<?php
$test = array("(hello world)", "hello (world)");

foreach ($test as &$val) {
     if (preg_match("/^\(.*\)$/",$val)) {
        $val = substr($val,1,-1);
     }
}

print_r($test);

请编辑您的问题,以显示您尝试了什么,以及该尝试遇到了什么问题。此外,还需要完全定义问题-例如,是否需要匹配左大括号和右大括号?如果有多个大括号
((hello)world)
,或不匹配的
(hello)world)
)hello()world()
etc@Rizier123否。请再次阅读问题。仅供参考,您可以使用
数组walk()代替
数组映射()
并将修改后的克隆数组存储到同一变量
$test
带有一个pass-by-reference参数。如果没有键,我想不出一个好的方法来修改它。我们必须使用
array_walk()
,因为没有通过引用传递键的好方法。我没有完全理解你,但你根本不需要传递键。啊,嗯,你是说
array_map(函数($item)use(&$test){$item=preg_replace(…);},$test)?它的目的是什么?!我觉得这不太对。我刚刚在你的例子中提供了
array\u walk
over
array\u map
array\u walk($test,function(&$value){$value=preg\u replace('.^\(.*)$\'$1',$value)})
array_walk($test, function(&$value) {
    $value = preg_replace('/^\((.*)\)$/', '$1', $value);
});
<?php
$test = array("(hello world)", "hello (world)");

foreach ($test as &$val) {
     if (preg_match("/^\(.*\)$/",$val)) {
        $val = substr($val,1,-1);
     }
}

print_r($test);