将具有多个空格的字符串转换为数组的更好方法
Better way to convert string with multiple spaces into array
我正在读取文件,每行都有多个空格。示例:
$line = 'Testing Area 1 10x10';
我需要将它转换成只有 3 个元素的数组,这样我就可以将它保存到 table。最终输出应该是这样的:
$final_array = array('Testing Area', '1', '10x10');
到目前为止我是这样做的:
// read by line
foreach(explode(PHP_EOL, $contents) as $line) {
// split line by 2 spaces coz distance between `1` and `10x10` is atleast 2 spaces
$arr = explode(' ', $line);
// But because `Testing Area` and `1` has so many spaces between them,
// exploding the $line results to empty elements.
// So I need to create another array for the final output.
$final_array = array();
// loop through $arr to check if value is empty
// if not empty, push to $final array
foreach ($arr as $value) {
if (!empty($value)) {
array_push($final_array, $value);
}
}
// insert into table the elements of $final_array according to its column
}
有没有更好的方法来代替遍历数组并检查每个元素是否为空?
请注意,我有多个文件要读取,每个文件至少包含 200 行。
假设分割的标准是两个或多个空格,我们可以在这里尝试使用preg_split
:
$line = 'Testing Area 1 10x10';
$final_array = preg_split("/\s{2,}/", $line);
print_r($final_array);
这会打印:
Array
(
[0] => Testing Area
[1] => 1
[2] => 10x10
)
使用preg_split()
,以2个或更多空格作为分隔符。
$array = preg_split('/\s{2,}/', $line);
我正在读取文件,每行都有多个空格。示例:
$line = 'Testing Area 1 10x10';
我需要将它转换成只有 3 个元素的数组,这样我就可以将它保存到 table。最终输出应该是这样的:
$final_array = array('Testing Area', '1', '10x10');
到目前为止我是这样做的:
// read by line
foreach(explode(PHP_EOL, $contents) as $line) {
// split line by 2 spaces coz distance between `1` and `10x10` is atleast 2 spaces
$arr = explode(' ', $line);
// But because `Testing Area` and `1` has so many spaces between them,
// exploding the $line results to empty elements.
// So I need to create another array for the final output.
$final_array = array();
// loop through $arr to check if value is empty
// if not empty, push to $final array
foreach ($arr as $value) {
if (!empty($value)) {
array_push($final_array, $value);
}
}
// insert into table the elements of $final_array according to its column
}
有没有更好的方法来代替遍历数组并检查每个元素是否为空? 请注意,我有多个文件要读取,每个文件至少包含 200 行。
假设分割的标准是两个或多个空格,我们可以在这里尝试使用preg_split
:
$line = 'Testing Area 1 10x10';
$final_array = preg_split("/\s{2,}/", $line);
print_r($final_array);
这会打印:
Array
(
[0] => Testing Area
[1] => 1
[2] => 10x10
)
使用preg_split()
,以2个或更多空格作为分隔符。
$array = preg_split('/\s{2,}/', $line);