%s 不会停止在模式 [已关闭] 中的硬编码管道处匹配

问题描述 投票:0回答:2

所以我有很多带有格式化信息的文件,因此有几个文件包含这种格式的多行: ID|访问次数|信息|姓名

当我运行以下代码时,$id 和 $visits 正确匹配,只有 $info 和 $name 似乎有某种问题。 $info 包含第二个 | 之后的所有内容分隔符。 $name 为空。

我错过了什么吗?

<?php
$dir = new DirectoryIterator('./logs/');
foreach ($dir as $file) {
   if (!$file->isDot()) {
       $filename = $file->getFilename();
       $currentfile = fopen("./logs/$filename","r");
       if ($currentfile) {
           while (($line = fgets($currentfile)) !== false) {
               $n = sscanf($line, "%d|%d|%s|%s", $id,$visits,$info,$name);
               print "$name was visited $visits times<br>";
           }
           fclose($currentfile);
       } else {
          print "Error: Couldn't open file.<br>";
       }
   }
}
?>
php scanf greedy
2个回答
2
投票
$dir = new DirectoryIterator('./logs/');
foreach ($dir as $file) {
    if (!$file->isDot()) {
        $filename = $file->getFilename();
        $currentfile = fopen("./logs/{$filename}", "r");
        if ($currentfile) {
            while (($line = fgets($currentfile)) !== false) {
                $n = sscanf($line, "%d|%d|%[^|]|%s", $id, $visits, $info, $name);
                print "{$name} was visited {$visits} times<br>";
            }
            fclose($currentfile);
        } else {
            print "Error: Couldn't open file.<br>";
        }
    }
}

您需要将

%d|%d|%s|%s
替换为也可以包含正则表达式的
%d|%d|%[^|]|%s
%[^|]
读取除
|
之外的所有字符。由于您要在第三个分隔符中查找字符串,因此它会占用所有字符直到最后,从而使以下分隔符具有空文字值。由于您使用
|
作为分隔符,因此,您需要防止
|
读入
%s
以继续执行后续分隔符。当您具有某些分隔符时,数字可以轻松读取,但对于字符串而言则不容易读取,因为字符串可以是从数字到任何字符(包括分隔符,但
space
除外,因为这是保留的分隔符)。

这里,您需要使用正则表达式设置某些条件来匹配您想要的内容,并将其提取到变量中。

希望有帮助!


0
投票

很少有分隔符会造成此问题,例如:'.''|'

您必须使用其他分隔符才能使其正确。 供参考:http://php.net/manual/en/function.sscanf.php#81842

© www.soinside.com 2019 - 2024. All rights reserved.