从数组中删除括号

时间:2016-07-11 13:23:59

标签: php arrays

我想删除括号,只要它们位于给定刺痛的开头和结尾:

示例:

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

成为:

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

4 个答案:

答案 0 :(得分:4)

尝试使用array_map() anonymous functionpreg_replace()

$test = array("(hello world)", "hello (world)");
$test = array_map(function($item) {
    return preg_replace('/^\((.*)\)$/', '\1', $item);
}, $test);

例如:

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 >

正如@revo在评论中指出的那样,我们也可以修改数组以提高性能并减少内存使用:

array_walk($test, function(&$value) {
    $value = preg_replace('/^\((.*)\)$/', '$1', $value);
});

答案 1 :(得分:1)

您可以将preg_replacearray_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 worldhello world)

答案 2 :(得分:1)

您可以使用正则表达式:

例如

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

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

print_r($test);

打印:

  

阵   (       [0] =&gt;你好,世界       [1] =&gt;你好,世界)   )

答案 3 :(得分:0)

<?php

// if first character = "(" AND last character = ")"
if (substr($string, 0,1) == "(" && substr($string, 0,-1) == ")") 
{
    $string = substr($string, 1);
    $string = substr($string, 0,-1);
}