$handle = fopen("mytext.txt", "r");
echo fread($handle,filesize("mytext.txt"));
echo preg_match("/[0-9]/","",$handle);
fclose($handle);
我想打开一个文本文件,并找到文本中有多少数字。我试图使用preg_match
,但我认为这不是正确的方法。PHP文件处理hw
$handle = fopen("mytext.txt", "r");
echo fread($handle,filesize("mytext.txt"));
echo preg_match("/[0-9]/","",$handle);
fclose($handle);
我想打开一个文本文件,并找到文本中有多少数字。我试图使用preg_match
,但我认为这不是正确的方法。PHP文件处理hw
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。
它看起来像你的示例代码被截断,你可以编辑你的文章,以确保格式和完整列表包括 – Michael