PHP:计算字符串上的扩展出现次数

PHP: Counting Extensions Occurence on a String

我有一个网络服务 return 给我一个包含上传文件列表的字符串,使用 ', ' 作为分隔符。

示例: 01467_rbt.csv, 0152t.csv, 35302.png

我需要做的是计算每个扩展名在字符串中出现的次数。

上一个示例的预期结果: .csv: 2 file(s); .png: 1 file(s)

我正在使用 preg_match_all 使用 .\w\w\w 作为正则表达式,但我不知道执行以下代码的最佳方法。

你可以做类似的东西:

$string = '01467_rbt.csv, 0152t.csv, 35302.png';
$array = explode(", ", $string); // get an array with each filename

$result = array();

foreach ($array as $value) {
    $dexplode = explode(".", $value); // explode the filename on .
    $extension = end($dexplode); // get the last --> extension

    if(isset($result[$extension])) // if it's an existing extension
        $result[$extension]++; // add 1
    else // if not existing
        $result[$extension]=1; // init to 1
}

var_dump($result);

并且,例如,要有多少个csv文件:

$result["csv"];

这是 var_dump() 的结果:

array (size=2)
  'csv' => int 2
  'png' => int 1

编辑:

您有多种可能找到文件扩展名:

$filename = 'mypic.gif';

// 1. The "explode/end" approach
$ext = end(explode('.', $filename));

// 2. The "strrchr" approach
$ext = substr(strrchr($filename, '.'), 1);

// 3. The "strrpos" approach
$ext = substr($filename, strrpos($filename, '.') + 1);

// 4. The "preg_replace" approach
$ext = preg_replace('/^.*\.([^.]+)$/D', '', $filename);

// 5. The "never use this" approach
//   From: http://php.about.com/od/finishedphp1/qt/file_ext_PHP.htm
$exts = split("[/\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];

更多详情here