doufu6196 2014-09-06 16:47
浏览 23
已采纳

字符串替换不起作用。 我忽略了什么吗?

I am trying my best to build a generator for the fantastic WordPress Plugin Boilerplate by Tom Mc Farlin. All works out quite well. I load the file from github, extract it to a directory and replace all needed strings like 'plugin_name', 'Your name ' etc.

Unfortunately there is a protected class variable named $plugin_name and some other tiny bits. So I decided to 'repair' some flaws after replacing, like this:

// Repair some flaws
$repair_file = $newAbsDir.'/plugin-name/trunk/includes/class-'.$new_plugin_name.'.php';
$repair_file_content = file_get_contents($repair_file);
$repair_strings = array(
    '$'.$new_plugin_name => '$plugin_name', 
    '$this->'.$new_plugin_name => '$this->plugin_name', 
    'get_'.$new_plugin_name => 'get_plugin_name'
);
foreach($repair_strings as $string => $replace){
    $repair_file_content = str_replace($string, $replace, $repair_file_content);
}
file_put_contents($repair_file, $repair_file_content);

BUt what seemed to work quite well with my glob array of files, does simply not work with the above. I assume it has something to do with the dollar sign. Does anybody have an idea how to fix this?

  • 写回答

2条回答 默认 最新

  • douluo5937 2014-09-07 12:45
    关注

    From PHP manual:

    If search and replace are arrays, then str_replace() takes a value from each array and uses them to search and replace on subject.

    So, it's like Elias Van Ootegem said, do a simple str_replace() without foreach(). The array values are passed on the literal array and the keys on array_keys(). And as the array keys are the ones to be searched, you have to invert the array:

    $repair_strings = array(
        '$plugin_name' => '$'.$new_plugin_name, 
        '$this->plugin_name' => '$this->'.$new_plugin_name, 
        'get_plugin_name' => 'get_'.$new_plugin_name
    );
    $repair_file_content = str_replace( array_keys( $repair_strings ), $repair_strings, $repair_file_content );
    

    Inverting the array is just to keep the logic search => replace, but to use your original array it's a matter of:

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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图