【问题标题】:searching for and replacing base64 image string with php用php搜索和替换base64图像字符串
【发布时间】:2012-07-08 02:41:51
【问题描述】:

我有一个从数据库中获取的 HTML 字符串。该字符串有几个 base64 图像,我需要用应该从 base64 图像字符串生成的图像文件替换它们。我不知道我该怎么做。任何指针将不胜感激。

原始 html

预期的 html

【问题讨论】:

    标签: php image replace


    【解决方案1】:
    echo preg_replace_callback('#(<img\s(?>(?!src=)[^>])*?src=")data:image/(gif|png|jpeg);base64,([\w=+/]++)("[^>]*>)#', "data_to_img", $content);
    
    function data_to_img($match) {
        list(, $img, $type, $base64, $end) = $match;
    
        $bin = base64_decode($base64);
        $md5 = md5($bin);   // generate a new temporary filename
        $fn = "tmp/img/$md5.$type";
        file_exists($fn) or file_put_contents($fn, $bin);
    
        return "$img$fn$end";  // new <img> tag
    }
    

    【讨论】:

    • 感谢您的快速回复。是否可以在 preg_replace_callback 函数中使用类方法(函数)作为回调?
    • 你可以使用任何可调用的符号,在这里查看它们:php.net/manual/en/language.types.callable.php
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    相关资源
    最近更新 更多