解析文件名而不将字符分隔成段

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

我正在开展一个项目,我从政府网站下载了数千条法律(合法性均按顺序排列)。我正在尝试拆分文件的名称,以便我可以在我的网站中更好地对它们进行排序。文件是这样设计的

48600003801.html

我正在

scandir()
函数上运行 foreach 循环。我有大约 20,000 多个这样的文件。我想做以下事情:

Chapter: 486
Section: 380

      CH.   ART.  SEC.
Split 486 | 000 | 0380 | 1

// PHP code
$files = scandir('stathtml/');
    foreach ($files as $file) {

        // Change this to a split function and then echo certain parts
        // of it out to test.
        echo $file . "<br>";

    }

我该如何拆分这样的字符串类型,因为它们的长度几乎都不同?

php string split filenames text-parsing
2个回答
1
投票

试试这个:

// PHP code
    $files = scandir('stathtml/');
        foreach ($files as $file) {
            $arr1 = substr($files, -5);
            $arr1 = substr($arr1, 4);
            $arr2 = substr($files, 3);
            echo $file . "<br>";
            echo "section ".$arr1 . "<br>";
            echo "chapter".$arr2 . "<br>";
        }

0
投票

sscanf()
是解析不包含分隔符的文件名的理想工具。 通过自定义占位符来表示每个子字符串的长度和质量。

%s
占位符将贪婪地匹配非空白字符。
%d
将贪婪地匹配数字并返回 int 类型匹配(无前导零)。 可以通过在
%
和类型字母之间插入指定的长度来指定显式长度。 演示

$file = '48600003801.html';

sscanf($file, '%03s%03s%04s%d', $chp, $art, $sec, $num);
var_export([$chp, $art, $sec, $num]);

sscanf($file, '%03d%03d%04d%d', $chp, $art, $sec, $num);
var_export([$chp, $art, $sec, $num]);

输出:

array (
  0 => '486',
  1 => '000',
  2 => '0380',
  3 => 1,
)

array (
  0 => 486,
  1 => 0,
  2 => 380,
  3 => 1,
)
© www.soinside.com 2019 - 2024. All rights reserved.