关于文件名和数字的PHP正则表达式

时间:2013-02-26 09:36:00

标签: php regex

如何捕获和提交文件名

输入:

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

Outout:

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
    )

)

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

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

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

3 个答案:

答案 0 :(得分: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
    )
)

答案 1 :(得分:0)

在php.Explode中尝试explode函数,该字符串包含filename.Use'。'作为爆炸分隔符和extraxt分解数组来获取文件名。

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

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

答案 2 :(得分:0)

使用basename()功能检索没有扩展名的文件名。