Last active
December 24, 2015 03:18
-
-
Save wudi/2f6d1e83a3fd4c6b3929 to your computer and use it in GitHub Desktop.
html-include-replace.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
/** | |
* Auth: Eagle.Wu | |
* Usage: | |
* 1、 /bin/sh file.php /dir | |
* 2、 cd /dir && /bin/sh file.php | |
* 3、 cp file.php /usr/local/bin/file && chmod +x /usr/local/bin/file && && file /dir | |
*/ | |
$startTime = microtime(true); | |
$suffix = '.html'; | |
$path = isset($argv[1]) ? isset($argv[1]) : posix_getcwd(); | |
$pattern = '/include\s*\{([^\}]+)\}\s*;/i'; | |
if(!is_dir($path)){ | |
echo "{$path} not directory.\n"; | |
exit(1); | |
} | |
$dir = opendir($path); | |
while (($file = readdir($dir)) !== false ) | |
{ | |
if($file == '.' || $file == '..'){ | |
continue; | |
} | |
if(strstr($file, '.') == $suffix){ | |
$filePath = $path . DIRECTORY_SEPARATOR . $file; | |
if(!is_writable($filePath)){ | |
echo "{$filePath} not writable.\n"; | |
continue; | |
} | |
$content = file_get_contents($filePath); | |
if(empty($content)){ | |
echo "{$filePath} is empty.\n"; | |
continue; | |
} | |
echo "Start\t-----> $filePath [Processing]\n"; | |
$content = preg_replace_callback($pattern, function($matches) use($filePath, $path){ | |
$_filePath = $path.DIRECTORY_SEPARATOR.$matches[1]; | |
if(!file_exists($_filePath)){ | |
echo "[Warring]: {$_filePath} not exists.\n"; | |
return ''; | |
} | |
if(!is_readable($_filePath)){ | |
echo "[Warring]: {$_filePath} not readable.\n"; | |
return ''; | |
} | |
echo "\tInclude -----> $_filePath [ok]\n"; | |
return file_get_contents($_filePath); | |
}, $content); | |
$ret = file_put_contents($filePath, $content); | |
if($ret){ | |
echo "End\t-----> $filePath [ok]\n"; | |
}else{ | |
echo "End\t-----> $filePath [Failed]\n"; | |
} | |
} | |
} | |
closedir($dir); | |
echo sprintf("\nFinished: %.6fs\n", microtime(true)-$startTime); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment