How to remove parentheses from values in an array?

7

I have an array and I need to remove all parentheses from all the values of this array. Follow the array:

$array = array(
    "chave1" => "(valor1)",
    "chave2" => "(valor2)",
    "chave3" => "(valor3)"
);

I need you to look like this:

$array = array(
    "chave1" => "valor1",
    "chave2" => "valor2",
    "chave3" => "valor3"
);

How can I do this using php?

    
asked by anonymous 03.01.2017 / 13:20

4 answers

10

You can use array_map() to apply an anonymous function to each item in the array. The substitution is for the str_replace() that searches for ( and ) and swap for nothing. A new array is generated:

$array = array(
        "chave1" => "(valor1)",
        "chave2" => "(valor2)",
        "chave3" => "(valor3)"
);

$novo = array_map(function($item){return str_replace(array('(', ')'), array('', ''), $item);}, $array);

echo "<pre>";
print_r($n);

Another option is to use array_walk() it does almost the same thing as array_map() but does not generate a new array, as the argument is passed by reference to change is made in the element itself.

array_walk($array, function(&$item){ $item = str_replace(array('(', ')'), array('', ''), $item);});

echo "<pre>";
print_r($array);
    
03.01.2017 / 13:27
5

You can easily change using the array_walk function together with a good regular expression.

  

array_walk - Apply a user supplied function to every member of an array

As the manual says, array_walk traverses all elements of an array by applying to each of them a function provided as a parameter.

To remove the parentheses, I'll use a regular expression. The% w / w in question is simple% w / w%. Translating means "anything in parentheses that are not parentheses."

As previously reported, you need to provide a function for ER . In this case, a function will be created as \(([^()]+)\) . The function is as follows:

$callback = function(&$value , $key) {
    preg_match('/\(([^()]+)\)/' , $value , $matches);

    $value = $matches[1];
};

Applying your array with array_walk .

array_walk($array , $callback);

You'll get the following result:

array(3) { ["chave1"]=> string(6) "valor1" ["chave2"]=> string(6) "valor2" ["chave3"]=> string(6) "valor3" }
    
03.01.2017 / 13:32
4

You can try this:

foreach($array as $key => $value):
    $array[$key] = str_replace('(', '', $value);
    $array[$key] = str_replace(')', '', $array[$key]);
endforeach;

Basically I ran all elements of the array and changed ( and ) to nothing.

    
03.01.2017 / 13:27
4

You can loop through the array with a foreach loop, use str_replace to pull out the parentheses and write the parenthesized items in a new array:

$parentheses = array('(', ')');
$newArray = [];
foreach ($array as $value) {
  $value = str_replace($parentheses, '', $value);
  $newArray[] = $value;
}
    
03.01.2017 / 13:28