Skip to content

Instantly share code, notes, and snippets.

@shellus
Created August 27, 2017 13:35
Show Gist options
  • Save shellus/a837ae255fc7ad9764e00745d5119c1c to your computer and use it in GitHub Desktop.
Save shellus/a837ae255fc7ad9764e00745d5119c1c to your computer and use it in GitHub Desktop.
replace img src attributes in a html string
<?php
/**
* Created by PhpStorm.
* User: shellus
* Date: 2017-08-27
* Time: 20:56
*/
/**
* replace img src attributes in a html string
* @param $html
* @param $callback
* @return string
*/
function replace_img_src_callback($html, $callback)
{
return preg_replace_callback("/(<img.*?>)/", function ($matches) use ($callback) {
$imgHtml = $matches[0];
return preg_replace_callback("/src=[\"'](.*?)[\"']/", function ($matches) use ($callback) {
$src = $matches[1];
$src = $callback($src);
return "src=\"$src\"";
}, $imgHtml);
}, $html);
}
$str = 'foo<img src="https://www.google.com/images/branding/product/ico/googleg_lodp.ico">';
var_dump(replace_img_src_callback($str, function($src){
// note a empty string
// if($src == "") return "";
// download the $src to localhost
// return localhost url
return "http://xxx.xxx/xxx.xxx";
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment