【问题标题】:PHP File Handling hwPHP文件处理硬件
【发布时间】:2016-05-12 14:22:48
【问题描述】:
$handle = fopen("mytext.txt", "r");

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

fclose($handle);

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

【问题讨论】:

  • 您的示例代码似乎被截断了,您能否编辑您的帖子以确保包含格式和完整列表

标签: php server-side file-handling filehandle


【解决方案1】:

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

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

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

fclose($handle);

【讨论】:

    【解决方案2】:

    您应该使用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,您可能会得到更好的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 2010-09-30
      • 2016-01-03
      • 1970-01-01
      相关资源
      最近更新 更多