Sam Skirrow Sam Skirrow - 5 months ago 15
PHP Question

PHP how to use str_replace in a foreach loop

I have the following code:

foreach($html->find('#portfolioImages img') as $element)
$element->src = str_replace("~100x50", "~540x540", $element->src);
echo '<img src="http://www.spotlight.com' . $element->src . '" /><br>';


To explain,
$element->src
returns the source of an image returned by using a page crawling script (hence the
$html->find
). However, I need to replace the "~100x50" part of each src with "~540x540"

The problem with this code is it works on the first image, but then doesn't return any other images (there should be several). What is the proper way to use str_replace in a foreach loop?

Answer

you need to put the braces in order to foreach work as you expect:

foreach($html->find('#portfolioImages img') as $element) {
    $element->src = str_replace("~100x50", "~540x540", $element->src);
    echo '<img src="http://www.spotlight.com' . $element->src . '" /><br>';
}

when you use foreach without braces, it only executes the first line after it. So, the foreach in your code are running the first line many times, but the second line after it is only run one time