我正在使用scandir()
在包含R12345.jpg, R12345_2.jpg, R12346.jpg, R12346_2.jpg, R12346_3.jpg
等文件的目录中构建图像文件名数组。
我想知道将此数组拆分为以下元素的最佳方法:
R12345,,jpg
R12345,2,jpg
R12346,,jpg
R12346,2,jpg
R12346,3,jpg
感谢。
答案 0 :(得分:5)
您可以尝试:
$input = 'R12345_2.jpg';
$output = explode(',', str_replace(array('.', '_'), ',', $input);
它会返回一个数组:
array (size=3)
0 => string 'R12345' (length=6)
1 => string '2' (length=1)
2 => string 'jpg' (length=3)
击> <击> 撞击>
或使用正则表达式:
preg_match('/^([^_]*)_?(\d+)?\.(.*)$/', $input, $output);
输出:
array (size=4)
0 => string 'R12345.jpg' (length=10)
1 => string 'R12345' (length=6)
2 => string '' (length=0)
3 => string 'jpg' (length=3)
使用
array_shift($output);
您可以快速删除第一个元素。
答案 1 :(得分:0)
$files_arr //this contains your files
$final_arr=array(); //this contains final array
foreach($files_arr as $k=>$v)
{
$test_arr = explode('.',$v);
$t = explode('_',$test_arr[0]);
if(empty($t[1])) $t[1] = '';
$t[2] = $test_arr[1];
array_push($final_arr[$k],$t);
}
print_r($final_arr);
答案 2 :(得分:0)
使用explode()函数拆分初始数组,然后使用preg_match拆分单个部分:
$str = 'R12345.jpg, R12345_2.jpg, R12346.jpg, R12346_2.jpg, R12346_3.jpg';
$files = explode(',', $str);
$result = array();
foreach ($files as $file) {
$matches = array();
preg_match('/^([A-Za-z0-9]+)_?([0-9]*)\.(jpg|png|gif)/$', trim($file), $matches);
array_shift($matches); // Remove first match that is the whole file name
array_push($result, $matches);
}
答案 3 :(得分:0)
<?php
//Result of $files = implode(', ',$scandirResult);
$files = 'R12345.jpg, R12345_2.jpg, R12346.jpg, R12346_2.jpg, R12346_3.jpg';
preg_match_all('#((R\d+)_?(\d*))\.(\w+)#',$files,$output);
$result = array();
foreach($output[2] as $key => $name)
{
$result[] = array($name,$output[3][$key],$output[4][$key]);
}
echo '<pre>'.print_r($result,true).'</pre>';
?>
输出:
Array
(
[0] => Array
(
[0] => R12345
[1] =>
[2] => jpg
)
[1] => Array
(
[0] => R12345
[1] => 2
[2] => jpg
)
[2] => Array
(
[0] => R12346
[1] =>
[2] => jpg
)
[3] => Array
(
[0] => R12346
[1] => 2
[2] => jpg
)
[4] => Array
(
[0] => R12346
[1] => 3
[2] => jpg
)
)