duanfu6160 2015-04-04 04:35
浏览 133
已采纳

如何在执行PHP“preg_replace”时在base64中动态编码

I'm parsing a js file server side, with regex, in order to find all the elements of template I have to change before actually sending the code to the client. Things work ok for files but not for images.

The key idea is to classically encode them in base64, and use atob() to decode. I don't know if PHP is able to encode an image in base64 while doing a regex (?)

If yes, that could explain that I get no results. If not, it would be so nice if someone could take a little time to help me to understand the problem illustrated below.

Parser (PHP) :

$content = file_get_contents('myfile.js');
$pattern = '/__image\[(.*)\]__/i';
$url = '$1';
$complete = preg_replace($pattern, base64_encode(file_get_contents($url)), $content);
echo json_encode($complete);

Client side controller (JS) :

... //result of an ajax call
content = JSON.parse(responseText);
eval(content); //data are safe

File which contains the call to the image (JS) :

    config.design = { 
            logo : { 
                    ...
            },  
            image : { 
                    ...
                    background : background : 'url(data:image/jpg;base64,__image[css/images/logo/logo.jpg]__)'
            },  
            baseline : { 
                    ...
            }   
    }; 

Result :

background-image: url(data:image/jpg;base64,); //[Error] Failed to load resource ... (kCFErrorDomainCFNetwork erreur -10). (data:image/jpg;base64,false, line 0)
  • 写回答

1条回答 默认 最新

  • duanmu6231 2015-04-04 12:41
    关注

    Here is a sample code with preg_replace_callback showing how you can modify submatches.

    $str = "background : background : 'url(data:image/jpg;base64,__image[css/images/logo/logo.jpg]__)'
    background : background : 'url(data:image/jpg;base64,__image[css/images/logo/logo.jpg]__)'"; 
    $re = "/([^<>]*?__image\[)(.*?)(\]__\)')/i"; 
    $str = preg_replace_callback($re, function ($matches) {
            return str_replace($matches[1], "background-image: url(", 
                   str_replace($matches[3], ");",
                   str_replace($matches[2], "<<base64-file>>", $matches[0])));
              }, $str);
    print ($str);
    

    Output:

    background-image: url(<<base64-file>>);background-image: url(<<base64-file>>);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化