删除数组元素中的空白区域,修剪不起作用

时间:2017-01-03 10:27:09

标签: php laravel laravel-5 laravel-5.2 laravel-5.3

我有这个数组:

array:4 [▼
  0 => "juego de tronos"
  1 => "tagaryen"
  2 => "house targaryen"
  3 => "casa targaryen"
]

我希望得到这个结果:

array:4 [▼
  0 => "juegodetronos"
  1 => "tagaryen"
  2 => "housetargaryen"
  3 => "casatargaryen"
]

我正在使用此功能但不起作用:array_map('trim',$myarray)

4 个答案:

答案 0 :(得分:7)

trim()仅从开头和结尾删除空格。你可能想要

array_map(function($a){ 
    return str_replace(' ', '', $a); 
}, $myarray);

答案 1 :(得分:2)

trim()从中删除空间,您可以使用循环替换空格' '与''或者以下列方式使用相同的array_map

array_map(function($variable){ 
    return str_replace(" ", "", $variable); 
}, $myarray);

OR

$myarray = array(0 => "juego de tronos",1 => "tagaryen",2 => "house targaryen",3 => "casatargaryen");
$newarr = [];
foreach($myarray as $arr)
{
   array_push($newarr,(str_replace(' ', '', $arr)));
}
echo "<pre>"; print_r($newarr); echo "</pre>";

答案 2 :(得分:2)

我们已经完成了这个

请尝试以下代码。工作正常。我已经查过了。

$array1 = array(
            "0" => "juego de tronos",
            "1" => "tagaryen",
            "2" => "house targaryen",
            "3" => "casa targaryen"
        );
        $newArray = array();
        foreach ($array1 as $data){
            $data = str_replace(" ","",$data);
            $newArray[]=$data;
        }

答案 3 :(得分:1)

$arrayWithSpace = array(
    "juego de tronos", 
    "tagaryen", 
    "house targaryen", 
    "casa targaryen"
);

$arrayWithoutSpace = array_map(function($value){ 
     return str_replace(' ', '', $value); 
}, $arrayWithSpace);

print_R($arrayWithoutSpace);