Created
February 6, 2013 09:39
-
-
Save wokamoto/4721440 to your computer and use it in GitHub Desktop.
[PHP] 特定ディレクトリ内の全 *.html ファイルの中身を相対URLに変更
This file contains 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
<?php | |
$dir = './path/'; | |
$org_url = 'http://example.com/'; | |
function scan_file($dir, $file_type = '{*.html,*.css,*.js,*.gif,*.png,*.jpg,*.zip,*.xml}') { | |
$list = $tmp = array(); | |
foreach(glob($dir . '*/', GLOB_ONLYDIR) as $child_dir) { | |
if ($tmp = scan_file($child_dir, $file_type)) { | |
$list = array_merge($list, $tmp); | |
} | |
} | |
foreach(glob($dir . $file_type, GLOB_BRACE) as $image) { | |
$list[] = $image; | |
} | |
return $list; | |
} | |
function replace_relative_URI($content, $home_url) { | |
$parsed = parse_url($home_url); | |
$replace = $parsed['scheme'] . '://' . $parsed['host']; | |
if (isset($parsed['port'])) | |
$replace .= ':'.$parsed['port']; | |
$pattern = array( | |
'# (href|src|action)="'.preg_quote($replace).'([^"]*)"#ism', | |
"# (href|src|action)='".preg_quote($replace)."([^']*)'#ism", | |
); | |
$content = preg_replace($pattern, ' $1="$2"', $content); | |
$pattern = '#<(meta [^>]*property=[\'"]og:[^\'"]*[\'"] [^>]*content=|link [^>]*rel=[\'"]canonical[\'"] [^>]*href=|link [^>]*rel=[\'"]shortlink[\'"] [^>]*href=|data-href=|data-url=)[\'"](/[^\'"]*)[\'"]([^>]*)>#uism'; | |
$content = preg_replace($pattern, '<$1"'.$replace.'$2"$3>', $content); | |
return $content; | |
} | |
$files = scan_file($dir, '{*.html}'); | |
$info = new FInfo(FILEINFO_MIME_TYPE); | |
foreach ($files as $filename) { | |
$filetype = $info->file($filename); | |
if ( $filetype == 'text/plain') { | |
if (preg_match('/\.css$/i', $filename)) | |
$filetype = 'text/css'; | |
else if (preg_match('/\.js$/i', $filename)) | |
$filetype = 'application/x-javascript'; | |
else if (preg_match('/\.html?$/i', $filename)) | |
$filetype = 'text/html'; | |
else if (preg_match('/\.xml$/i', $filename)) | |
$filetype = 'application/xml'; | |
} | |
echo $filetype . ':' . str_replace($dir, '', $filename) . "\n"; | |
$file_content = replace_relative_URI(file_get_contents($filename), $org_url); | |
rename( $filename, $filename . '.org'); | |
file_put_contents( $filename, $file_content ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment