Changing some data inside the src parameter of the image and adding hyperlinks to the image PHP DOM
I have some text with images inside it. For example like this
texttext<img src="2011-08-15/4/img/123.JPG" alt="" width="528" height="394.3458646616541" >texttext
Now I need some code that searches for the image, finds it, checks if it has class. If no then I want to change it's soruce from this
2011-08-15/4/img/123.JPG
to this
2011-08-15/4/mini/123.JPG
And then add hyperlink to image plus remove width and height params from img tag, so the final result must be like this
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
Here is the code that searches and all I need is code that does all the manipulations.
$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();
}
}
Is there a way to solve this problem ? If you can't write the whole code maybe you could help me with small examples ?
- How to change something inside src parameter and save .
- How to remove width and height 开发者_如何学Cparameters from img tag .
- How to add hyperlink tag to im tag.
I need this 3 techniques
$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();
- loop images
- get the ones without class
- change src, width, height whatever you want, remove attributes ...
- add
a
Element beforeimg
Element - add
href
attribute and whatever you want - remove
img
Element with no class - append
img
toa
Element
精彩评论