我有一个将HTML数据发送到服务器的文本框,在这个数据中,图像是用Base64编码的,用我的PHP脚本,我想从HTML中提取Base64数据然后将其写入图像文件并替换Base64图像数据与刚刚创建的图像文件的URL。到目前为止,这是我的代码:
//this function takes the raw HTML data and extracts the Base64 data
function testFormat($string){
$count = substr_count($string, "data:image");
$title = "hello";
for($i=0;$i<$count;$i++){
$b64 = $this->get_string_between($string, "img src=\"", "\" ");
while(strpos($b64, "data:") !== false){
$rnd = rand(0, 99999);
$img_url = $title . "-" . $rnd . ".jpg";
$this->convertBase64ToImage($b64, $img_url);
$string = str_replace($b64, $img_url, $string);
}
}
return $string;
}
//this function converts Base64 text to image
function convertBase64ToImage($base64_string, $output_file){
// open the output file for writing
$ifp = fopen( $output_file, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );
// add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
// clean up the file resource
fclose( $ifp );
return $output_file;
}
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$str = file_get_contents("file.txt");
var_dump($ps->testFormat($str));
"file.txt"
https://pastebin.com/B5UTAH0n
问题是我的代码仅在只有一个(base64)图像时有效,如果有2个(如示例中)或更多图像,它只替换第一个出现,其他Base64出现不被替换。我怎样才能用URL替换每个occerrence?