现在我有:
$path2 = $file_list1;
$dir_handle2 = @opendir($path2) or die("Unable to open $path2");
while ($file2 = readdir($dir_handle2)) {
if($file2 == "." || $file2 == ".." || $file2 == "index.php" )
continue;
echo ''.$file2.'<br />';
}
closedir($dir_handle2);
echo '<br />';
当返回$ file2时,字符串中的最后4个字符将始终以数字加上文件扩展名.txt结尾,如下所示:
file_name_here1.txt
some_other-file10.txt
所以我的问题是,我怎么能分开$ file2所以它返回两个部分的字符串,$ file_name和$ call_number这样?:
echo 'File: '.$file_name.' Call: '.call_number.'<br />';
返回:
File: file_name_here Call: 1
File: some_other-file Call: 10
而不是:
echo ''.$file2.'<br />';
返回:
file_name_here1.txt
some_other-file10.txt
...谢谢
答案 0 :(得分:1)
试试这个,你需要使用Regex来有效地做到这一点
$filename = reset(explode(".", $file2))
preg_match("#(^[a-zA-Z\_\-]*)([\d]*)#", $filename, $matches);
$fullMatch = $matches[0];
$file = $matches[1];
$call = $matches[2];
echo "File: " . $file . " Call: " . $call;
答案 1 :(得分:1)
使用正则表达式:
preg_match("/^(.+)(\d+)(\..+)$/", $file2, $matches);
$file_name = $matches[1];
$call_number = $matches[2];
答案 2 :(得分:1)
我是Regex的大力支持者,但我决定在这里略有不同。看看:
$file = 'file_name_here19.txt';
$file_parts = pathinfo($file);
$name = $file_parts['filename'];
$call = '';
$char = substr($name, strlen($name) - 1);
while(ord($char) >= 48 && ord($char) <= 57) {
$call = $char . $call;
$name = substr($name, 0, strlen($name) - 1);
$char = substr($name, strlen($name) - 1);
}
echo 'Name: ' . $name . ' Call: ' . $call;
答案 3 :(得分:0)
pathinfo()
function切断文件扩展名。使用preg_match()
function将姓名与号码分开。
3。
while (...) {
...
$filename; // some_other-file10.txt
$filename = pathinfo($filename, PATHINFO_FILENAME); // some_other-file10
preg_match('/^(?<name>.*?)(?<number>\d+)$/', $filename, $match);
$match['name']; // some_other-file
$match['number']; // 10
echo "File: {$match['name']} Call: {$match['number']}\n";
}