我有一个名为$output
的字符串,它返回一个像这样的列表
Object One
Object Two
Object Three
Object Four
Object Five
Object Six
我想使用像这样的爆炸把它变成一个数组:
explode("\n", $output);
但是,开头有很多空行和随机空格。有没有办法删除所有这些,以便我留下一个可用的数组?
答案 0 :(得分:1)
您可以使用array_filter
过滤掉数组中的空字符串
array_filter(explode("\n", $output));
要删除开头的空格,请使用array_map
$result = array_filter(explode("\n", $output));
array_map('trim', $result);
答案 1 :(得分:1)
您可以trim()
生成explode()
生成的每一行,并忽略修剪后的empty strings。
或者您可以使用preg_split()
作为分隔符,包含至少包含一个换行符的任何白色空格序列:
$text = <<<E
Object One
Object Two
Object Three
Object Four
Object Five
Object Six
E;
var_dump(preg_split('/\s*\n(\s*\n)*\s*/', trim($text)));
输出结果为:
array(6) {
[0]=>
string(10) "Object One"
[1]=>
string(10) "Object Two"
[2]=>
string(12) "Object Three"
[3]=>
string(11) "Object Four"
[4]=>
string(11) "Object Five"
[5]=>
string(10) "Object Six"
}
regex
:
\s* # zero or more (*) whitespaces (\s)
\n # a newline character
( # beginning of a group
\s*\n # zero or more whitespaces followed by a newline
) # end of the group
* # zero or more repetitions of the previous expression (the group)
\s* # zero of more whitespaces
答案 2 :(得分:0)
<?php
$data = " Object One
Object Two
Object Three
Object Four
Object Five
Object Six";
$data = explode("\n", $data);
$finalArray = array();
foreach($data as $value){
if(!empty(trim($value))){
$finalArray[] = trim($value);
}
}
print_r($finalArray);
输出:
Array ( [0] => Object One [1] => Object Two [2] => Object Three [3] => Object Four [4] => Object Five [5] => Object Six )
答案 3 :(得分:0)
试试这个......
<强>输入强>
$data = " Object One
Object Two
Object Three
Object Four
Object Five
Object Six";
<强>解决方案强>
$result = array_filter(array_map('trim',explode("\n", $data)));
echo "<pre>"; print_r($result);
<强>输出强>
Array
(
[0] => Object One
[3] => Object Two
[6] => Object Three
[8] => Object Four
[9] => Object Five
[11] => Object Six
)
答案 4 :(得分:0)
使用preg_split()
对所有换行序列(\R
)进行拆分,并包括零个或多个前导或尾随空白序列(\s*)
。如果输入字符串的开头或结尾处存在与换行符序列不相邻的空格,请预先修剪输入。
代码:(Demo)
var_export(preg_split('~\s*\R\s*~', trim($string), -1, PREG_SPLIT_NO_EMPTY));
输出:
array (
0 => 'Object One',
1 => 'Object Two',
2 => 'Object Three',
3 => 'Object Four',
4 => 'Object Five',
5 => 'Object Six',
)