在文本文件中,我有一个这样的文件:
Olivia
7
Sophia
8
Abigail
9
Elizabeth
10
Chloe
11
Samantha
12
Run Code Online (Sandbox Code Playgroud)
我想打印出所有名称而忽略这些数字.
出于某种原因,它不起作用 - 它不会打印任何东西?
<?php
$file_handle = fopen("names.txt", "rb");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
if (!is_numeric((int)$line_of_text)) {
echo $line_of_text;
echo "<br />";
}
}
fclose($file_handle);
?>
Run Code Online (Sandbox Code Playgroud)
你正在投射每一行(int).所以即使是字符串的行也会变为0(零).
您可以将代码更改为:
!is_numeric($line_of_text)
Run Code Online (Sandbox Code Playgroud)
注意: is_numeric()将返回true小数和科学记数法.如果您严格确定该行是否包含数字,我建议ctype_digit()
您还需要trim($line_of_text)为与fgets()包括换行符.
代码里面while():
$line_of_text = trim(fgets($file_handle));
if (!ctype_digit($line_of_text)) {
echo $line_of_text;
echo "<br />";
}
Run Code Online (Sandbox Code Playgroud)
!is_numeric((int)$line_of_text)
Run Code Online (Sandbox Code Playgroud)
想一想:你把这条线投射到一条线上int,所以不管它以前是什么,它都会成为一个数字.然后你要测试它是不是数字.当然它是数字的,因为你做到了.因此,条件总是错误的.
int在测试之前停止投射is_numeric.