Vikram Rao
Vikram Rao

Reputation: 1078

Alter image path using str_replace or preg_replace

Hello friends I am having trouble getting desired results using str_replace (); function of PHP.

My code is like this:

<?php ob_start (); /* Start Buffering */

$layout = 'climate';

?>

<div>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pellentesque.</p>

<img src="images/industry/pic1.jpg"/>
<img src="products/images/industry/pic2.jpg"/>
<img src="samples/products/images/industry/pic3.jpg"/>

</div>

<?php ob_get_contents();  /* Get the Buffer */

$content = str_replace('/desktop/', $layout . '/images/', $layout);

echo $content;

ob_end_flush (); /* Send Output to the browser */

?>

Now here what I am trying to do is let the entire page get generated, then I want to get the generated page and replace a specific word in it's paths. Finally send the buffer to Browser.

Please Note:

I am very new to PHP hence please request you to help me correct this code to correct syntax.

These paths in my output are generated by the CMS I am using hence I have no control on them.

The value to $layout variable is assigned by another PHP function. I did not mention that snippet just to avoid confusion.

Since my theme is Non-JavaScript I do not intend to use any JavaScript.

Desired output:

I want /industry/ to be replaced by the value of /$layout/ in entire page before sending it to the browser.

<div>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc pellentesque.</p>

<img src="images/climate/pic1.jpg"/>
<img src="products/images/climate/pic2.jpg"/>
<img src="samples/products/images/climate/pic3.jpg"/>

</div>

Lastly :

Please feel free to suggest any other solution if you feel is better than this one.

Upvotes: 0

Views: 662

Answers (1)

nickb
nickb

Reputation: 59699

You can get the buffer and close it with ob_get_clean(), then do your replacement and echo the $content, which will send it to the browser.

$content = ob_get_clean();  
$content = str_replace('/industry/', '/' . $layout . '/', $content);
echo $content;

Upvotes: 2

Related Questions