1

如何捕获和归档文件名

输入:

news.jpg
news_1.png
asnews_2.gif
asnews_3.jpeg
aw_news_4.jpg
aw_news.gif

输出:

Array
(
[0] => Array
    (
        [0] => news
        [1] => news_1
        [2] => asnews_2
        [3] => asnews_3
        [4] => aw_news_4
        [5] => aw_news
    )

[1] => Array
    (
        [0] => 
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
        [5] => 
    )

[2] => Array
    (
        [0] => news
        [1] => news
        [2] => asnews
        [3] => asnews
        [4] => aw_news
        [5] => aw_news
    )

)

我在 PHP 中尝试过使用preg_match_allpreg_replace_callback,但我不知道如何正确使用。

preg_match_all('/(?: _???_ (?:_([\d]+))?$/im', $fullname, $result);  // $fullname - string

这是一个类似的例子 - /(?:(?:_([\d]+))?(.[^.]+))$/。你可以改变这个。

4

3 回答 3

2
$result = array (array (), array (), array ());

$dir = opendir ("/tmp");
while (($file = readdir ($dir)) !== false)
{
  if ($file == '.' || $file == '..') continue;

  $matches = array ();
  preg_match ('/^(([^.]*?)(?:_([0-9]*))?)(?:\.|$)/', $file, $matches);

  $result [0][] = $matches [1];
  $result [1][] = $matches [3];
  $result [2][] = $matches [2];
}
closedir ($dir);

print_r ($result);

输出是:

Array
(
    [0] => Array
    (
        [0] => news
        [1] => news_1
        [2] => asnews_2
        [3] => asnews_3
        [4] => aw_news_4
        [5] => aw_news
    )

    [1] => Array
    (
        [0] =>
        [1] => 1
        [2] => 2
        [3] => 3
        [4] => 4
        [5] =>
    )

    [2] => Array
    (
        [0] => news
        [1] => news
        [2] => asnews
        [3] => asnews
        [4] => aw_news
        [5] => aw_news
    )
)
于 2013-02-26T09:45:15.360 回答
0

在 php 中尝试explode函数。分解包含文件名的字符串。使用 '.' 作为爆炸分隔符并提取爆炸数组以获取文件名。

有关爆炸手册的参考,请尝试此

http://php.net/manual/en/function.explode.php

于 2013-02-26T09:38:01.890 回答
0

使用basename()函数检索不带扩展名的文件名。

于 2013-02-26T09:39:31.830 回答