实现功能
1、移除class属性
2、src追加域名
3、重新附着class属性
实现方法
function replaceImageTags($content, $domain = '', $class = '')
{
$rule = array(
'tag' => '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i',
'src' => '/(<img .*?src=\")(.*?)(\".*?>)/is',
'url' => '/^http(s)?:\\/\\/.+/i',
'filter' => '/ class="([^\"]*)"/isU',
'class' => '/(<img .*?src=\")(.*?)(\".*?)(.*?>)/is',
);
preg_match_all($rule['tag'], $content, $matches);
$imgs = $matches[0];
if ($imgs) {
foreach ($imgs as $img) {
$out = preg_replace($rule['filter'], '', $img);
if ($domain) {
preg_match($rule['tag'], $out, $match);
$src = $match[1];
if (!preg_match($rule['url'], $src)) {
$out = preg_replace($rule['src'], '${1}' . $domain . '${2}${3}', $out);
}
}
if ($class) {
$out = preg_replace($rule['class'], '${1}${2}${3} class="' . $class . '"${4}', $out);
}
$content = str_replace($img, $out, $content);
}
}
return $content;
}
调用测试
//$scheme = (isset($_SERVER['HTTPS']) && 'on' === strtolower($_SERVER['HTTPS'])) || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 'https' === strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'])) ? 'https' : 'http';
if (isset($_SERVER['HTTPS']) && 'on' === strtolower($_SERVER['HTTPS'])) {
$scheme = 'https';
} else if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 'https' === strtolower($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$scheme = 'https';
} else {
$scheme = 'http';
}
$domain = $scheme . '://' . $_SERVER['SERVER_NAME'] . '/';
$class = 'fix';
$content = '<section><h1>welcome</h1><p><img src="images/a.png" border="0" alt=""><img src="images/b.png" border="0" alt="" /><img src="https://www.xxx.com/images/c.png" title="" class="net"></p></section>';
$content = replaceImageTags($content, $domain, $class);
var_dump($content);
|