0

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);
3
  • Can you provide some sample URLs, and show us what you expect ? Commented Sep 28, 2014 at 22:46
  • I'm worried when I see (?[!="). Try to use an online tool like regex101.com. I'm also a bit worried about the random type casts you make. Commented Sep 28, 2014 at 22:48
  • I know I'm really not good at that. My image will always be like that: [... ="image.jpg" ...] Commented Sep 28, 2014 at 22:49

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

2 Comments

instead of using .* use [^"]* otherwise something like position="left" poster="image.jpg" will give you wrong results.
it don't works with attribute before: test1="something" test2="image.jpg"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.