$handle = fopen("mytext.txt", "r");
echo fread($handle,filesize("mytext.txt"));
echo preg_match("/[0-9]/","",$handle);
fclose($handle);我想打开一个文本文件,找出文本中有多少位数字。我试图使用preg_match,但我认为这不是正确的方法。
发布于 2016-05-12 14:37:41
preg_match()接受资源句柄。这是不正确的:
$handle = fopen("mytext.txt", "r");
$content = fread($handle,filesize("mytext.txt"));
$noDigit = preg_match("/[0-9]/","",$content);
fclose($handle);发布于 2016-05-12 14:40:16
您应该使用全部()。preg_match()只匹配第一个结果。
另外,regex正在寻找单个数值。您应该使用\d+来匹配一个或多个数字的所有实例(即匹配1、20和3580243)。
$subject = "String with numbers 4 8 15 16 23 42";
$matches = array();
preg_match_all('\d+', $subject, $matches);然后,要对它们进行计数,只需循环遍历$matches中的匹配并增加一个计数器变量。
编辑:而且,使用内容()可能会得到更好的结果,而不是使用fopen、fread、fclose。
https://stackoverflow.com/questions/37189814
复制相似问题