1

I am having some files in a folder as follows: ss1.txt, ss2.txt, .., ss9.txt, ss10.txt, ss11.txt, .., ss19.txt, ss20.txt.

When I tried to fetch these files using preg_match, I got the result in the order:

ss1.txt, ss10.txt, ss11.txt, ... ss19.txt, ss2.txt, ss20.txt.

What I need exactly is as follows:

ss1.txt, ss2.txt, .., ss9.txt, ss10.txt, ss11.txt, .., ss19.txt, ss20.txt.

The expression that I am using is as below:

    '/_ss[1-9]+\.txt/' 
4

2 回答 2

0

首先构建前 0-9 个匹配项的列表:

<?php
$files = array("ss1.txt", "ss2.txt", "ss14.txt");
$sorted = array();
$a_string = "";
foreach ($files as &$file) {
    preg_match ('/_ss[1-9]\.txt/', file, matches)
    $a_string = $matches[0];
    if (isset($a_string)) {
       array_push($sorted, $a_string); } }
unset($file); 

然后构建 11-20 匹配的第二个列表:

foreach ($files as &$file) {
    preg_match ('/_ss[0-9][0-9]\.txt/', file, matches)
    $a_string = $matches[0];
    if (isset($a_string)) {
       array_push($sorted, $a_string); } }
unset($file); 
?>

另一种方法是使用preg_match_all返回两个匹配列表而不循环,但前提是您的数据已经在一个大字符串中(或者您想要转换它)。

$giant_text = join (" ", $files)
$list_of_single_dig = preg_match_all('/_ss\d\.txt/', $giant_text, $matches);
$list_of_double_dig = preg_match_all('/_ss\d\d\.txt/', $giant_text, $matches);
$sorted = array_merge ($list_of_single_dig, $list_of_double_dig)
于 2013-06-11T06:38:49.010 回答
0

看看natsort

$sorted = natsort($unsorted_files);
于 2013-06-11T07:36:13.040 回答