Created
March 14, 2013 10:18
-
-
Save gomasaba/5160264 to your computer and use it in GitHub Desktop.
htmlタグの画像のパスを変える
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
/** | |
* 画像のパスを変える | |
* @param {[type]} $html [description] | |
* @return {[type]} [description] | |
*/ | |
function convert($basedir,$html){ | |
$img_pattern = '/<img .*?src="(.*?)".*?>/i'; | |
$src_pattern = '/src="(.*?)"/'; | |
/*---------------------------------------------- | |
* | |
* 画像変換処理 | |
* <imgタグからパスを切り出して取得したIMGタグをbasedirをつけて返す | |
* 新しい<imgタグを返す | |
----------------------------------------------*/ | |
$replace_img = function($basedir,$data) use ($src_pattern){ | |
preg_match_all($src_pattern,$data,$match,PREG_OFFSET_CAPTURE); | |
if(isset($match[0][0])){ | |
foreach($match[1] as $key => $val){ | |
$orign = $val[0]; | |
$offset = $val[1]; | |
$parse = parse_url($orign); | |
$replace = ''; | |
if(isset($parse['scheme']) && isset($parse['host'])){ | |
$replace .= $parse['scheme'].'://'.$parse['host'].DS; | |
} | |
$replace .= ltrim(rtrim($basedir,DS),DS).$parse['path']; | |
$data = str_replace($orign, $replace, $data); | |
} | |
} | |
return $data; | |
}; | |
//画像があれば置換 | |
preg_match_all($img_pattern,$html,$match,PREG_OFFSET_CAPTURE); | |
if(isset($match[0][0])){ | |
foreach($match[0] as $key => $val){ | |
$orign = $val[0]; | |
$offset = $val[1]; | |
$replace = $replace_img($basedir,$orign); | |
$html = str_replace($orign, $replace,$html); | |
} | |
} | |
return $html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment