dslfq06464 2016-02-10 07:57 采纳率: 0%
浏览 114
已采纳

在PHP中按组分组preg_replace

I have a string

$cmd = "java -jar yuicompressor-2.4.8.jar --type *file_type* *original_file* > *new_file*";

And I want to replace like below

java -jar yuicompressor-2.4.8.jar --type css css/style.css > css/style.min.css

What I did is

$cmd = str_replace("*original_file*", $v, $cmd);
$cmd = str_replace("*new_file*", "$k", $cmd);
$cmd = str_replace("*file_type*", "css", $cmd);

I'm looking for a sort way like preg_replace. Any suggestion will be appreciated.

  • 写回答

2条回答 默认 最新

  • dongyuelian9602 2016-02-10 08:09
    关注

    I don't see any reason why a regular expression should make sense here. Instead I suggest you simply use the str_replace function in its ability to make multiple replacements at once:

    <?php
    $subject = 'java -jar yuicompressor-2.4.8.jar --type *file_type* *original_file* > *new_file*';
    
    $catalog = [
      '*file_type*' => 'css',
      '*original_file*' => 'css/style.css',
      '*new_file*' => 'css/style.min.css'
    
    ];
    
    var_dump(str_replace(array_keys($catalog), $catalog, $subject));
    

    The output obviously is:

    string(78) "java -jar yuicompressor-2.4.8.jar --type css css/style.css > css/style.min.css"
    

    This is a simple and robust approach and should be much more efficient than using regex based pattern matching.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改