Skip to content Skip to sidebar Skip to footer

Using Regex To Wrap Images In Tags

I've been using regex to wrap my images in < a > tags and altering their paths etc. I know using dom for this is better, having read a lot of threads about wrapping, but I'm

Solution 1:

I've left out a few details, but here's how I would do it using DOMDocument:

$s = <<<EOM
<p><img src="/uploads/userdirs/admin/1160501362291.png" alt="" width="1280" height="960" /></p>
<p><img src="/uploads/userdirs/admin/100_Bullets_68_1280x1024.jpg" alt="" width="1280" height="1024" /></p>
EOM;

$d = new DOMDocument;
$d->loadHTML($s);

foreach ($d->getElementsByTagName('img') as$img) {
    $img_src = $img->attributes->getNamedItem('src')->nodeValue;
    if (0 === strncasecmp($img_src, '/uploads/userdirs/admin', 23)) {
        $a = $d->createElement('a');

        $a->setAttribute('class', 'gallery');
        $a->setAttribute('rel', 'whatever');
        $a->setAttribute('href', '/uploads/userdirs/username/' . $img_src);

        // disconnect image tag from parent$img->parentNode->replaceChild($a, $img);

        // and move to anchor$a->appendChild($img);
    }
}

echo$d->saveHTML();

Solution 2:

You should change .* in your regular expression with [^>]*. The latter means: any character expect than >. Because regular expression gets as long match as possible. Without this additional condition, this ends up with two <img>'s matched.

Post a Comment for "Using Regex To Wrap Images In Tags"