Created
August 27, 2017 13:35
-
-
Save shellus/a837ae255fc7ad9764e00745d5119c1c to your computer and use it in GitHub Desktop.
replace img src attributes in a html string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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