2011-08-16 24 views
0

我有一些带有图像的文字。 例如像这样更改图像的src参数内的一些数据并将超链接添加到图像PHP DOM

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(); 
    } 
} 

有没有办法解决这个问题?如果你不能写出整个代码,也许你可以用小例子来帮助我?

  1. 如何更改src参数内的内容并保存。
  2. 如何从img标签中删除宽度和高度参数。
  3. 如何将超链接标签添加到im标签。

我需要这3个技术

回答

1
$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(); 
  1. 线圈图像
  2. 让那些没有类
  3. 变化SRC,宽,高任何你想要的,删除属性...
  4. add a元素img元素
  5. 添加href属性,任何你想要的
  6. 删除img元素与无级
  7. 追加imga
+0

非常感谢,开始实施此技术为我的项目。怎么样从img标签中删除宽度和高度参数?你有setAttribute认为哪些改变属性值,但是如何删除属性? – David

+0

@David阅读帖子...''img-> removeAttribute('width');''..我在里面设置了代码:) –

+0

Oh sorry。我的错。谢谢你。我认为这是我的问题的完整答案。谢谢! – David