Reputation: 345
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?
Upvotes: 1
Views: 76
Reputation: 345
D'oh ...
$My_fantastic_plugin differs slightly from $my_fantastic_plugin. Sorry for the hassle and thank you for the good advice with $repair_file_content = str_replace( array_keys( $repair_strings ), $repair_strings, $repair_file_content );
Upvotes: 0
Reputation: 26055
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 );
Upvotes: 1