【发布时间】:2016-07-07 10:53:18
【问题描述】:
在 php 中,我想用我的自定义 url 替换 html 中的图像 src。为此,我制作了这样的功能
function replace_img_src($img_tag) {
$doc = new DOMDocument();
$doc->loadHTML($img_tag);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
$old_src = $tag->getAttribute('src');
$new_url = rawurlencode($old_src);
$new_src_url = get_template_directory_uri() . '/img.php?img='.$new_url;
$tag->setAttribute('src', $new_src_url);
}
return $doc->saveHTML();
}
它工作正常,但它返回像这样的总 html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p class='\"\"'>hello world</p><div class='\"medium-insert-images\"'><img src="http://test.com/dev/projects/newatarlife/wp-content/themes/atarlife/img.php?img=%5C%22https%3A%2F%2Fpixabay.com%2Fget%2Feb32b40620f41c2ad65a5854e44a4092e27fe5c818b517469df8c97ba5ee_640.jpg%5C%22"></div><div class='\"medium-insert-buttons\"' contenteditable='\"false\"' style='\"left:' top: display: none>
<a class='\"medium-insert-buttons-show\"'> </a>
<ul class='\"medium-insert-buttons-addons\"' style='\"display:' none><li><a data-addon='\"images\"' data-action='\"add\"' class='\"medium-insert-action\"'><span class='\"fa' fa-camera></span></a></li>
<li><a data-addon='\"embeds\"' data-action='\"add\"' class='\"medium-insert-action\"'><span class='\"fa' fa-youtube-play></span></a></li>
</ul></div></body></html>
我只想要正文中的内容。不是整个 html。
【问题讨论】:
-
为什么你所有的html属性都有两对引号
'"...."'?
标签: php html preg-replace