1

I'm working on a simple comments removal script in PHP. What I'd like to do is loop this entire script for all the files in the same directory. At this point I'm not concerned with subdirectories or subfolder. This example only has 1 file. I know we need to do a do..while loop but what would be the proper syntax?

<?php
$file='home.html';
$page = file_get_contents($file);
$current = preg_replace('<!--[^\[](.*?)-->', '', $page);
file_put_contents($file, $current);
echo $current;
?>

I have a folder filled with *.html files so this script would read each file with the *.html extension and apply the preg_replace.

Thanks in advance!

V

Viktor
  • 517
  • 5
  • 23

2 Answers2

2

I wrote a function similar to your needs not long ago:

private function getFilesByPattern($pattern = '*.html', $flags = 0)
{
    $files = glob($pattern, $flags);
    foreach (glob(dirname($pattern) . '/*', GLOB_ONLYDIR | GLOB_NOSORT) as $dir) {
        $files = array_merge($files, $this->getTestFiles($dir . '/' . basename($pattern), $flags));
    }

    return $files;
}

This function also searches recusively through sub directories! For $flags look into the flags of glob: http://php.net/manual/de/function.glob.php

Can be called like this: getTestFiles('../src/directory/*.html')

FMK
  • 1,062
  • 1
  • 14
  • 25
1
foreach (glob("*.html") as $file) {
$page = file_get_contents($file);
$current = preg_replace('<!--[^\[](.*?)-->', '', $page);
file_put_contents($file, $current);
echo $file . "<br>";
}

This works. It removes all the html comments from every html file in a folder. Thanks for pointing me in the right direction!

Viktor
  • 517
  • 5
  • 23