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条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算