简体   繁体   中英

How to remove spaces within folders using PHP

给定路径/ books / Aaronovitch,Ben / Rivers of London / 9780575097568,如何使用PHP重命名实际的文件夹名称以删除空格?

You can try the following

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

Output

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

Function

/**
 * 
 * @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 ;
}

Php function str_replace:

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

and then use the rename function.

rename($path, $newPath);

This will walk down each level of the hierarchy, renaming each component if it contains spaces.

$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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM