PHP 文件处理硬件

PHP File Handling hw

$handle = fopen("mytext.txt", "r");

echo fread($handle,filesize("mytext.txt"));
echo preg_match("/[0-9]/","",$handle);

fclose($handle);

我想打开一个文本文件并找出文本中有多少位数字。我尝试使用 preg_match 但我认为这不是正确的方法。

preg_match() 接受资源句柄。哪个是不正确的:

$handle = fopen("mytext.txt", "r");

$content = fread($handle,filesize("mytext.txt"));
$noDigit = preg_match("/[0-9]/","",$content);

fclose($handle);

您应该使用 preg_match_all()。 preg_match() 只会匹配第一个结果。

此外,您的正则表达式正在查找单个数值。您应该使用 \d+ 来匹配一个或多个数字的所有实例(即匹配 1、20 和 3580243)。

$subject = "String with numbers 4 8 15 16 23 42";
$matches = array();
preg_match_all('\d+', $subject, $matches);

然后,要对它们进行计数,您可以循环遍历 $matches 中的匹配项并增加一个计数器变量。

编辑:此外,使用 file_get_contents() 而不是使用 fopen、fread、fclose 可能会获得更好的结果。