John Davidson

How to replace PHP code in a file having newlinse


I got some files to change by clicking a button. To go for it, i have the old string to replace, saved in database, and also the new one.
On the click button, it executes a function that is gonna find the old string in the PHP file, then gonna replace it by the new one. (Final goal is to automate the PHP edits in a web software after an update).

My problem is that it perfectly works on short strings (without newline), but as soon as there is a newline into the file, nothing happens.

This is my actual code :

    $path = '/mypath/' . $item['path'];
$old_code = $item['old_code'];
$new_code = $item['new_code'];

$pos = strpos(file_get_contents($path), $old_code);
$file = file_get_contents($path);
$str = str_replace($old_code, $new_code, $file);
file_put_contents($path, $str);

$pos is "true" if my $old_code doesn't have any newline.
I tried to use preg_match to remove \n, but the problem is that when i'll have to push my edits on the file with file_put_contents, every newline will also disapear.

Example of non-working str_replace :

echo "ok";     echo 'hey there is some spaces before'
echo 'this is a sentence';
$menu = ['test1', 'test200'];
$url = "/link/to/test";
$div = "echo \"<div class='central_container' align='center'>\";";

Do you have any idea for resolving this ?

My Answer:
not taking into account the possibility of the old code being on multiple lines. To handle this, you can use the `preg_replace` function with the `s` modifier to make the dot (`.`) match newlines as well. Here's an updated version of your code:

$path = '/mypath/' . $item['path'];
$old_code = $item['old_code'];
$new_code = $item['new_code'];

$file = file_get_contents($path);
$str = preg_replace('/' . preg_quote($old_code, '/') . '/s', $new_code, $file);
file_put_contents($path, $str);

In this code snippet, `preg_quote` is used to escape any special characters in the old code before using it in the regular expression pattern. The `s` modifier at the end of the pattern allows the dot (`.`) to match newlines as well.

This should now properly replace the old code with the new code even if the old code spans multiple lines in the PHP file.

Rate this post

4 of 5 based on 7668 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us