开发者

Replacing the image within an image src tag

I have the following situation, I have an html file with 开发者_StackOverflowimage 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?


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);
?>


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" ...


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜