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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘