我可以避免foreach
生成的空数组吗
这是我的代码
$file="test.txt";
$open = file_get_contents($file);
$lines = explode(PHP_EOL, $open);
foreach($lines as $line){
$domain = preg_split('/'s+/', $line,-1,PREG_SPLIT_NO_EMPTY);
echo "<pre>";
var_dump($domain);
echo "$domain[0] OK";
echo "</pre>";
}
test.txt包含这个
www.google.com 2.2.2.3
www.test.com 2.2.2.3
www.example.com 2.2.2.3
在我运行脚本后,结果是这个
array(2) {
[0]=>
string(14) "www.google.com"
[1]=>
string(7) "2.2.2.3"
}
www.google.com OK
array(2) {
[0]=>
string(12) "www.test.com"
[1]=>
string(7) "2.2.2.3"
}
www.test.com OK
array(2) {
[0]=>
string(15) "www.example.com"
[1]=>
string(7) "2.2.2.3"
}
www.example.com OK
array(0) {
}
OK
array(0)
出现的原因是什么
在www.example.com或其他元素之后没有新行
我可以删除它还是干脆不生成它?
在最后一个域之后有一个额外的换行符或其他空白字符。
首先修剪文本文件内容:
$open = trim(file_get_contents($file));
您还可以检查循环中的行是否为空。
$file="test.txt";
$open = trim(file_get_contents($file)); // Either this..
$lines = explode(PHP_EOL, $open);
foreach($lines as $line){
if ($line === '') // Or this
continue;
$domain = preg_split('/'s+/', $line,-1,PREG_SPLIT_NO_EMPTY);
echo "<pre>";
var_dump($domain);
echo "$domain[0] OK";
echo "</pre>";
}
用检查包含最后一行的内容
var_dump($line);
如果它包含空字符串,只需添加一些检查:
if ( empty($line) ) {
continue;
}
我建议您使用SplFileObject
:
$path = "test.txt";
$file = new SplFileObject($path);
$file->setFlags(
SplFileObject::DROP_NEW_LINE # new line characters at the end of line
| SplFileObject::SKIP_EMPTY # skip empty lines, e.g. the one at the end
);
foreach ($file as $line)
{
$domain = preg_split('/'s+/', $line, -1, PREG_SPLIT_NO_EMPTY);
echo "<pre>", var_dump($domain), "$domain[0] OK", "</pre>";
}
它不仅支持您的问题内置(请参阅标志),还逐行解析文件,因此对于较大的文件,它不会将其完全转移到内存中。请参阅file
函数。
对于这样的示例,最好使用preg_match_all:
只是名字
<?php
$file = 'test.txt';
$open = file_get_contents($file);
preg_match_all('/^'S+/m', $open, $matches);
print_r($matches[0]);
Array
(
[0] => www.google.com
[1] => www.test.com
[2] => www.example.com
)
姓名和号码
<?php
$file = 'test.txt';
$open = file_get_contents($file);
preg_match_all('/^('S+)'s+('S+)$/m', $open, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => www.google.com 2.2.2.3
[1] => www.test.com 2.2.2.3
[2] => www.example.com 2.2.2.3
)
[1] => Array
(
[0] => www.google.com
[1] => www.test.com
[2] => www.example.com
)
[2] => Array
(
[0] => 2.2.2.3
[1] => 2.2.2.3
[2] => 2.2.2.3
)
)
$result = array_combine($matches[1], $matches[2]);
print_r($result);
Array
(
[www.google.com] => 2.2.2.3
[www.test.com] => 2.2.2.3
[www.example.com] => 2.2.2.3
)
我测试了您的代码,发现它运行得很好。。。我用相同的代码得到了这个输出
array(2) {
[0]=>
string(14) "www.google.com"
[1]=>
string(7) "2.2.2.3"
}
www.google.com OK
array(2) {
[0]=>
string(12) "www.test.com"
[1]=>
string(7) "2.2.2.3"
}
www.test.com OK
array(2) {
[0]=>
string(15) "www.example.com"
[1]=>
string(7) "2.2.2.3"
}
www.example.com OK
我认为你的文本文件中有一个新行[输入],请用退格删除它,它会很好用的。。