我发现有趣的问题,而我试图实现一些简单的东西,如分割字符串到数组。这里唯一的区别是,我试图从。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()和所有其他可能的解决方案/函数。数组过滤器和数组diff不删除空元素,不知道为什么…在我的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>";
}