开发者

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 ?

  1. How to change something inside src parameter and save .
  2. How to remove width and height 开发者_如何学Cparameters from img tag .
  3. 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();
  1. loop images
  2. get the ones without class
  3. change src, width, height whatever you want, remove attributes ...
  4. add a Element before img Element
  5. add href attribute and whatever you want
  6. remove img Element with no class
  7. append img to a Element
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜