我有一个包含等文件夹的目录
baseurl/2-435435435_323423/
baseurl/5_435435435_32423/
baseurl/3_543543_2342342/
现在我想将所有文件夹从原来的名称重命名为新名称,即截断最后一个由"_"分隔的部分。新名称将是
baseurl/2-435435435/
baseurl/5_435435435/
baseurl/3_543543543/
$path_from = 'E:/documents/';
if(file_exists($path_from)){
$files = scandir($path_from);
foreach($files as $key1 => $file) {
$newName = ? // I need this
rename($path_from.$file,$path_from.$newName);
}
}
或者让我知道是否在没有任何脚本的情况下,在windows中可以重命名批处理。
正如您提到的,只获得$newName
,只使用substr
和strrpos
。
strrpos
-查找字符串最后一次出现的数字位置
$str = 'baseurl/3_543543543_2342342/';
$pos = strrpos($str, "_");
if ($pos === false){
//do nothing
}else
$str = substr($str, 0, $pos)."/";
echo $newName = $str; //baseurl/3_543543543/
您可以使用strstr
$path_from = 'E:/documents/';
if(file_exists($path_from)){
$files = scandir($path_from);
foreach($files as $key1 => $file) {
$newName = strstr($file, '_', true);
rename($path_from.$file,$path_from.$newName);
}
}
例如
$str = 'baseurl/2-435435435_323423/';
$imagePreFix = strstr($str, '_', true);
echo $imagePreFix;
输出:
baseurl/2-435435435
$newName = substr($file, 0, strrpos($file, '_'));