如何使用PHP删除文件夹中的空格

时间:2012-10-12 23:59:07

标签: php directory

鉴于路径/书籍/ Aaronovitch,Ben / Rivers of London / 9780575097568,我如何使用PHP重命名实际文件夹名称以删除空格?

3 个答案:

答案 0 :(得分:1)

您可以尝试以下

echo renameRecrisive(__DIR__, "xx_x/yyy yyy/zz z/fff");

输出

 /public_html/www/stac/xx_x/yyy_yyy/zz_z

功能

/**
 * 
 * @param string $path Current path ending with a slash 
 * @param string $pathname Path you cant to rename
 * @param string $sep Optional Seprator
 */
function renameRecrisive($path, $pathname, $sep = "_") {
    $pathSplit = array_filter(explode("/", $pathname));
    $dir = $path;
    while ( $next = array_shift($pathSplit) ) {
        $current = $dir . "/" . $next;
        if (! is_dir($current)) {
            break;
        }
        if (preg_match('/\s/', $next)) {
            $newName = str_replace(" ", $sep, $next);
            rename($current, $dir . "/" . $newName);
            $dir .= "/" . $newName;
        } else {
            $dir .= "/" . $next;
        }
    }

    return $dir ;
}

答案 1 :(得分:0)

Php function str_replace:

$newPath = str_replace(' ', '', $path);

然后使用重命名功能。

rename($path, $newPath);

答案 2 :(得分:0)

这将沿着层次结构的每个级别向下走,如果它包含空格,则重命名每个组件。

$patharray = split('/', $path);
$newpatharray = str_replace(' ', '', $patharray);

$oldpath = $patharray[0];
$newpath = $newpatharray[0];
$i = 0;

while (true) {
  if ($patharray[$i] != $newpatharray[$i]) {
    rename($oldpath, $newpath);
  }
  $i++;
  if ($i >= count($patharray) {
    break;
  }
  $oldpath .= "/".$patharray[$i];
  $newpath .= "/".$newpatharray[$i];
}