mostafa
mostafa

Reputation: 41

remove parentheses from array

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)");

Upvotes: 2

Views: 895

Answers (4)

Will
Will

Reputation: 24689

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);
});

Upvotes: 4

Fredster
Fredster

Reputation: 776

<?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);
}

Upvotes: 0

apokryfos
apokryfos

Reputation: 40653

You could use regex:

For example

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

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

print_r($test);

Prints:

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

Upvotes: 1

Thamilhan
Thamilhan

Reputation: 13293

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)

Upvotes: 1

Related Questions