我有一些带图像的文本。例如像这个
texttext<img src="2011-08-15/4/img/123.JPG" alt="" width="528" height="394.3458646616541" >texttext
现在我需要一些代码来搜索图像,找到它,检查它是否有类。如果没有,那么我想从这个中更改它的soruce
2011-08-15/4/img/123.JPG
到这个
2011-08-15/4/mini/123.JPG
然后在图像中添加超链接,再从img标签中删除宽度和高度参数,所以最终的结果必须是这样的
texttext<a href="2011-08-15/4/img/123.JPG" class="colorbox cboxElement" style="margin: 0 5px 5px 0"><img src="2011-08-15/4/mini/123.JPG" alt=""></a>texttext
这是搜索的代码,我所需要的只是执行所有操作的代码。
$doc = new DOMDocument();
$doc->loadHTML($article_header);
$imgs = $doc->getElementsByTagName('img');
foreach ($imgs as $img) {
if(!$img->getAttribute('class')){
// ......Here must be some code that does all the work......
$article_header = $doc->saveXml();
}
}
有办法解决这个问题吗?如果你不能写完整的代码,也许你可以帮我举一些小例子?
- 如何更改src参数内部的内容并保存
- 如何从img标记中删除宽度和高度参数
- 如何将超链接标签添加到im标签
我需要这3种技术
$doc = new DOMDocument();
$doc->loadHTML($html);
$imgs = $doc->getElementsByTagName('img');
foreach ($imgs as $img) {
if(!$img->getAttribute('class')){
$src = $img->getAttribute('src');
$newSRC = str_replace('/img/', '/mini/', $src);
$img->setAttribute('src', $newSRC);
$img->setAttribute('width', '500'); // set new attribute value
$img->setAttribute('height', '500'); // set new attribute value
$img->setAttribute('title', 'New title'); // set new attribute and value
$img->removeAttribute('width'); // remove attribute
$img->removeAttribute('height'); // remove attribute
$href = $doc->createElement('a', '');
$addhref = $img->parentNode->insertBefore($href, $img);
$href->setAttribute('href', 'http://www.google.com');
$img->parentNode->removeChild($img);
$href->appendChild($img);
}
}
echo $doc->saveXml();
- 循环图像
- 拿那些没课的
- 随意更改src、width、height,删除属性
- 在
img
元素之前添加a
元素 - 添加
href
属性和您想要的任何内容 - 删除不带类的
img
元素 - 将
img
附加到a
元素