freaky
freaky

Reputation: 1010

PHP - 'preg_replace regex' all images' URL

I tried to replace all image URLs with an other image URL but I didn't success to correctly write the regex.

My images are not necessarily in an img tag with src="".

It is mostly enclosed with ="image url"

Content to replace for example:

[side_section poster="image.jpg" position="left" bgrepeat="no-repeat" bgcolor="#f6f6f6" paddingtop="70" paddingbot="70" txtcolor="" ]

$content = (string) preg_replace('/(?[!=")(http:\\/\\/.+(png|jpeg|jpg|gif|bmp))/Ui', './images/placeholder.png', (string) $content);

Upvotes: 0

Views: 2377

Answers (1)

Adam Sinclair
Adam Sinclair

Reputation: 1649

Here is what you need:

$content = '[side_section poster="image.jpg" position="left" bgrepeat="no-repeat" bgcolor="#f6f6f6" paddingtop="70" paddingbot="70" txtcolor="" ]';
$newContent = (string) preg_replace('/="([^"]*\.(?:png|jpeg|jpg|gif|bmp))"/', '="./images/placeholder.png"', (string) $content);
echo $newContent;

The regex used is: ="([^"]*\.(?:png|jpeg|jpg|gif|bmp))"

You can test the it here: DEMO

However the string that you use to replace your image paths should look like this: '="./images/placeholder.png"'

As an alternative use this function:

function replaceImg($content, $path)
{
    return (string) preg_replace('/="([^"]*\.(?:png|jpeg|jpg|gif|bmp))"/', '="'.$path.'"', (string) $content);
}   

example:

$content = '[side_section poster="image.jpg" position="left" bgrepeat="no-repeat" bgcolor="#f6f6f6" paddingtop="70" paddingbot="70" txtcolor="" ]';
echo replaceImg($content, './images/placeholder.png');

OUTPUT

[side_section poster="./images/placeholder.png" position="left" bgrepeat="no-repeat" bgcolor="#f6f6f6" paddingtop="70" paddingbot="70" txtcolor="" ]

example 2:

$content = 'position="left" poster="image.jpg"';
echo replaceImg($content, './images/placeholder.png');

OUTPUT

position="left" poster="./images/placeholder.png"

Upvotes: 2

Related Questions