Search code examples
phpregexpreg-replacefile-get-contentsfile-put-contents

How to replace a specific value in a hard-coded array inside of a php file?


I use a config.php file that returns an array. Before releasing the project, I usually manually change the 'apiKey' value that I use while developing in the file. I forget to perform this replacement sometimes, so I'm looking for a programmatical way to find this in a string version of the file:

'apiKey' => '1234567890'

and replace with this:

'apiKey' => 'YourAPIKeyHere'

The development apiKey value, spaces, tabs and formatting are inconsistent (Developer/IDE specific), so I guess there are wildcards for that?

Then I can just make the change in my deployment script.

Edit to show sample of config.php (which will be read into a string, edited, then re-written as a file).

<?php
return array(
// Comments with instruction exist throughout the file. They must remain.
'apiKey' => 'ecuhi3647325fdv23tjVncweuYtYTv532r3',
...
);

Edit: **There are instructional comments in the config.php file that must remain. So re-writing a modified array will lose the comments, and that is undesirable.


Solution

  • Save the config file's text in a variable called $content.

    Then call:

     $content = preg_replace("~'apiKey'\s*=>\s*'\K[^']+~", 'YourAPIKeyHere', $content, 1);
    

    Then overwrite the file with the updated variable.

    http://php.net/manual/en/function.preg-replace.php

    \s* means match zero or more whitespace characters.

    \K means restart the match from this point.

    [^']+ means match one or more non-single-quote character.

    Regex101 Demo

    PHP Demo