Aneesh
Aneesh

Reputation: 158

How to use regex in php to replace ALT and TITLE text in html

I have a html content as listed below.

<img title="" style="float: none;margin-right: 10px;margin-top: 10px;margin-bottom: 10px;" src="http://www.mbatious.com/sites/default/files/imagecache/Large/Distchart.jpg" class="imagecache-Large" alt="">

I would like to replace the empty alt and title text with the name of the image file (Distchart). How to do this using preg_replace in php? After performing replace operation, the html should be like

<img title="Distchart" style="float: none;margin-right: 10px;margin-top: 10px;margin-bottom: 10px;" src="http://www.mbatious.com/sites/default/files/imagecache/Large/Distchart.jpg" class="imagecache-Large" alt="Distchart">

Upvotes: 0

Views: 907

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

As Maxim Kumpan suggests it, the best way is to use the dom:

$doc = new DOMDocument();
@$doc->loadHTML($html);
$imgs = $doc->getElementsByTagName('img');
foreach($imgs as $img) {
    if (preg_match('~[^/]+(?=\.(?>gif|png|jpe?+g)$)~i', $img->getAttribute('src'), $match)) {
        $name = $match[0];
        if ($img->getAttribute('alt')=='') $img->setAttribute('alt', $name);
        if ($img->getAttribute('title')=='') $img->setAttribute('title', $name);
    }
}
$result = $doc->saveHTML();

Upvotes: 1

Goku Nymbus
Goku Nymbus

Reputation: 581

Try This

$oldhtml = '<img title="" style="float: none;margin-right: 10px;margin-top: 10px;margin-bottom: 10px;" src="http://www.mbatious.com/sites/default/files/imagecache/Large/Distchart.jpg" class="imagecache-Large" alt="">'

$newhtml = str_replace($oldhtml, 'alt=""', 'alt="Distchart"');

Upvotes: 0

Maxim Kumpan
Maxim Kumpan

Reputation: 2625

You are probably better off using DOMDocument for this. Regex'ing HTML is an ungrateful task.

Upvotes: 1

Related Questions