0

I have the following situation, I have an html file with image tags about 10 or more, but it varies. Now what I want to achieve is to replace the image src with a PHP function as example below

I want to replace something like this

<img src="image1.png" .... 
<img src="image2.png" .... 

with this

<img src="<?=imageResize('image1.png',20,15)?>" ...
<img src="<?=imageResize('image2.png',20,15)?>" ..`.

Is this possible?

Elitmiar
  • 35,072
  • 73
  • 180
  • 229

3 Answers3

3

Let's assume that the current page source is contained in $source. Try some regular expressions:

<?php
preg_replace ('/<img src="(.+)"/Ui', '<img src="<?=imageResize(\'\\1\',20,15)?>"', $source);
?>
rhino
  • 13,543
  • 9
  • 37
  • 39
0

I see 2 cases:

  • Your imageResize function resizes the image, creating a new one with a different name (something like image120x15.png) and returning a string with the image name. In this case you should do something like:
<img src="<?php echo imageResize('image1.png',20,15);?>" ...
  • Your imageResize actually resizes the initial image and overriding it. In this case, do something like:
<?php imageResize('image1.png',20,15);?>
<img src="image1.png" ...
CristiC
  • 22,068
  • 12
  • 57
  • 89
0

Capture output with output buffer and then apply regex for replace.

<?ob_strart();?>
<img src="image1.png" /> 
<img src="image2.png" />

<?php
$cnt = ob_get_clean();
$cnt = preg_replace ('/<img src="([^"]+)"/', '<img src="<?=imageResize(\'\\1\',20,15)?>"', $cnt);?>

For execute function imageresize you must run output in eval().

cubaguest
  • 544
  • 4
  • 8