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 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏