普通网友 2014-05-07 13:54
浏览 79
已采纳

PHP从数组内的字符串元素中删除括号

I am using in_array() function and trim() in order to detect strings in my array that include parenthesis (). Although that my current program is operating and meets my needs I would like to take it to the next level and make it more generic. Currently I am specifying the array position through "stack[2]".

$stack = array( "test-1" , "test-2" , "(test-3)" );

print_r($stack);

if ( in_array( "".$stack[2]."" , $stack , TRUE ) ) {
  $stack[2] = trim($stack[2], '()');
}

print_r($stack);

Before the trimming process:

Array
(
    [0] => test-1
    [1] => test-2
    [2] => (test-3)
)

After the trimming process:

Array
(
    [0] => test-1
    [1] => test-2
    [2] => test-3
)

I would like my program to search each value in the array, remove the () and save it on the same position. Sample of a test array is provided below:

$stack = array( "test-1" , "test-2" , "(test-3)" , "test-4" , "(test-5)" );

I am sure there is a way but I can not figure it how to do it.

Thank you for your time and effort.

展开全部

  • 写回答

3条回答 默认 最新

  • dongmi3203 2014-05-07 14:12
    关注

    Use a for loop and sizeof array:

    $stack = array( "test-1" , "test-2" , "(test-3)" , "test-4" , "(test-5)" );
    
    print_r($stack);
    
    for ($i = 0; $i < sizeof($stack); $i++){
       $stack[$i] = trim($stack[$i], '()');
    }
    
    print_r($stack);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?