str_split 从文件读取时在数组末尾添加空元素
str_split adding empty elements in array end when reading from file
我在尝试实现一些简单的操作(例如将字符串拆分为数组)时发现了一个有趣的问题。这里唯一的区别是我试图从 .txt 文件中获取字符串
我的代码如下:
$handle = fopen("input.txt", "r"); // open txt file
$iter = fgets($handle);
// here on first line I have the number of the strings which I will take. This will be the for loop limitation
for ($m = 0; $m < $iter; $m++)
{
$string = fgets($handle); // now getting the string
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}
这是我的 .txt 文件的内容
4
abc
abcba
abcd
cba
我尝试了 array_filter() 和所有其他可能的 solutions/functions。数组过滤器和数组差异没有删除空元素,不知道为什么......在我的 txt 文件中也没有空格或类似的东西。这是 str_split 函数中的错误吗?这背后有什么逻辑吗?
多余的空格是换行符。从技术上讲,除最后一行外,每一行都包含您看到的所有文本内容,外加一个换行符。
您可以通过例如
轻松摆脱它
$string = rtrim(fgets($handle));
此外,fgets($fp);
没有意义,因为没有变量 $fp
,根据您的上述代码应该是 fgets($handle);
。
修剪空格并需要将 fgets($fp)
更改为 fgets($handle)
,因为没有像 $fp
这样的变量。您需要将代码更新为
for ($m=0;$m<$iter;$m++)
{
$string = trim(fgets($handle)); //
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}
我在尝试实现一些简单的操作(例如将字符串拆分为数组)时发现了一个有趣的问题。这里唯一的区别是我试图从 .txt 文件中获取字符串 我的代码如下:
$handle = fopen("input.txt", "r"); // open txt file
$iter = fgets($handle);
// here on first line I have the number of the strings which I will take. This will be the for loop limitation
for ($m = 0; $m < $iter; $m++)
{
$string = fgets($handle); // now getting the string
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}
这是我的 .txt 文件的内容
4
abc
abcba
abcd
cba
我尝试了 array_filter() 和所有其他可能的 solutions/functions。数组过滤器和数组差异没有删除空元素,不知道为什么......在我的 txt 文件中也没有空格或类似的东西。这是 str_split 函数中的错误吗?这背后有什么逻辑吗?
多余的空格是换行符。从技术上讲,除最后一行外,每一行都包含您看到的所有文本内容,外加一个换行符。
您可以通过例如
轻松摆脱它$string = rtrim(fgets($handle));
此外,fgets($fp);
没有意义,因为没有变量 $fp
,根据您的上述代码应该是 fgets($handle);
。
修剪空格并需要将 fgets($fp)
更改为 fgets($handle)
,因为没有像 $fp
这样的变量。您需要将代码更新为
for ($m=0;$m<$iter;$m++)
{
$string = trim(fgets($handle)); //
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}