Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick and dirty rename of all files of one file extension to another (in this case, .html.php to .phtml)
<?php
$objects = new RecursiveIteratorIterator
(new RecursiveDirectoryIterator(__DIR__),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($objects as $path => $fileObject) {
$use = true;
$file_name = '';
$base_name = '';
if (is_dir($fileObject)) {
if ($fileObject->getFileName() == '.' || $fileObject->getFileName() == '..') {
} else {
$path = $fileObject->getPathName();
foreach (scandir($path) as $filename) {
if ($filename == '.' || $filename == '..') {
} else {
$newname = preg_replace('"\.html.php"', '.phtml', $filename);
rename($path . '/' . $filename, $path . '/' . $newname);
}
}
}
}
}
@AmyStephen

This comment has been minimized.

Copy link
Owner Author

@AmyStephen AmyStephen commented Oct 4, 2013

from +bobthecow

<?php 

for f in *.html.php; do mv "\$f" "\${f%.html.php}.phtml"; 
@peterjmit

This comment has been minimized.

Copy link

@peterjmit peterjmit commented Oct 4, 2013

Or if you have zmv

$ zmv -W '*.html.php' '*.phtml'

Also less indentation and code re-use...

<?php

function isIgnoredFile($filename) {
    return $filename == '.' || $filename == '..';
}

foreach ($objects as $path => $fileObject) {
    $use = true;
    $file_name = '';
    $base_name = '';

    if (!is_dir($fileObject) && isIgnoredFile($fileObject->getFileName())) {
        continue;
    }

    $path = $fileObject->getPathName();

    foreach (scandir($path) as $filename) {
        if (isIgnoredFile($filename)) {
            continue;
        } 

        $newname = preg_replace('"\.html.php"', '.phtml', $filename);
        rename($path . '/' . $filename, $path . '/' . $newname);
    }
}
@AmyStephen

This comment has been minimized.

Copy link
Owner Author

@AmyStephen AmyStephen commented Oct 4, 2013

Thanks again, @peterjmit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment