replace img tag src relative path to absolute path while leaving original absolute path remains the same.
<pre class="php" name="code"><?php
$STR = <<<EOD
<html>
<body>
<img src='/sites/default/files/my_web/1.gif' width='6' height='6'>
<img src='/sites/default/files/my_web/2.gif' width='6' height='6'>
<img src='sites/default/files/my_web/3.gif' width='6' height='6'>
<img src='sites/default/files/my_web/4.gif' width='6' height='6'>
<img width='6' height='6' src='/sites/default/files/my_web/5.gif'>
<img width='6' height='6' src='sites/default/files/my_web/6.gif'>
<br>
<img src="/sites/default/files/my_web/7.gif" width="6" height="6">
<img src="/sites/default/files/my_web/8.gif" width="6" height="6">
<img src="sites/default/files/my_web/9.gif" width="6" height="6">
<img src="sites/default/files/my_web/10.gif" width="6" height="6">
<img width="6" height="6" src="/sites/default/files/my_web/11.gif">
<img width="6" height="6" src="sites/default/files/my_web/12.gif">
<img src="http://google.com/sites/default/files/my_web/13.gif" width="6" height="6">
<a href="www.google.com">test</a>
<a href="http://www.google.com">test</a>
</body>
</html>
EOD;
$base_url = 'http://hmm.com/';
echo _replace_img_src_rel2abs($STR, $base_url) . PHP_EOL;
/**
* replace img tag src relative path to absolute path while leaving original absolute path remains the same.
* @param
* @return
*/
function _replace_img_src_rel2abs($STR, $base_url = 'http://gan.com') {
$base_url = rtrim($base_url, '/') . '/';
$matchArr = array();
$pattern = '/src=["\']([^"\':]+)["\']/ie';
// Note: If e modifier is set, preg_replace() does normal substitution of backreferences in the replacement string, evaluates it as PHP code, and uses the result for replacing the search string. Single quotes, double quotes, backslashes (\) and NULL chars will be escaped by backslashes in substituted backreferences.
return preg_replace($pattern, '_replace_img_src_rel2abs_add_base_url("$1", \$base_url);', $STR);
}
function _replace_img_src_rel2abs_add_base_url($STR = '', $base_url = '') {
return 'src="' . $base_url . ltrim($STR, '/') . '"';
}
?></pre>
Wednesday, February 16, 2011
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment