Find and Replace PHP Code in an Existing File

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
milton_1223
Forum Newbie
Posts: 4
Joined: Wed Apr 30, 2008 7:21 pm

Find and Replace PHP Code in an Existing File

Post by milton_1223 »

Hi everyone, :)

Lets say i made a mod to an existing scrip and want to implement it automatically. Im trying to make an installation script that would find some php files, open them, search for a specific line of code and replace it with another line in some cases and in some cases just insert some code below that line without replacing anything. Im up to the part of the file opening, but Im Stuck in the search. I can find ONE line of code, but in some cases I need to find a whole block. How can I find a specific block of code, and since im no expert, does the tabs in front of the code matters? I guess they do, but im not sure.

Let me show you an example of what im trying to do....

The first case is to find a single line of code like this...

Code: Select all

$userinfo['ship_country_list'] = getoptionlist('state_country', 'abb', 'name', 'WHERE type=\'' . COUNTRY . '\'', ($userinfo[ship_country] == "") ? $settings[country] : $userinfo[ship_country], 'name');
 
And insert a block of code like this beneath it....

Code: Select all

////////////// Start Account Type - Changes Required/////////////
$userinfo['account_type'] = getaccounttype($userinfo[group_in]);
$userinfo['account_type_list'] = getoptionlist('groups', 'id', 'name', 'WHERE visible=\'1\' ', $userinfo[group_in], 'name', 1);
////////////// End Account Type - Changes Required/////////////
The second case is to find a block of code like this...
** Notice the tabs in front of the code, since the original script file is formated like that i don´t know how to work arround this.

Code: Select all

                        while ($field = $DB_site->fetch_assoc($result))
                        {
                                if ($field['Field'] == 'password') $vars[password] = md5($vars[password]);
                                if (isset($vars[$field['Field']])) $query .= " `" . $field['Field'] . "`='" . sf($vars[$field['Field']]) . "',";
                        }
                        $query .= " `group_in`='" . $settings[defaultgroup] . "'";
and replace it with another block of code like this...

Code: Select all

////////////// Start Account Type - Changes Required/////////////
while ($field = $DB_site->fetch_assoc($result))
{
    if ($field['Field'] == 'password') $vars[password] = md5($vars[password]);
    if ($field['Field'] == 'username')
    {
        if (isset($vars[$field['Field']])) $query .= " `" . $field['Field'] . "`='" . sf($vars[$field['Field']]) . "'";
    }else{
        if ($field['Field'] == 'group_in')
        {
            if (getoptionlist('groups', 'id', 'name', 'WHERE visible=\'1\' ', "", 'name', 0) == "")
            {
                $query .= ", `" . $field['Field'] . "`='" . $settings[defaultgroup] . "'";
            }else{
                if (isset($vars[$field['Field']])) $query .= ", `" . $field['Field'] . "`='" . sf($vars[$field['Field']]) . "'";
            }
        }else{
            if (isset($vars[$field['Field']])) $query .= ", `" . $field['Field'] . "`='" . sf($vars[$field['Field']]) . "'";
        }
    }
}
////////////// End Account Type - Changes Required/////////////
if someone can help me on this or point me in the right direction would be much appreciated... :D
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Re: Find and Replace PHP Code in an Existing File

Post by Mordred »

I can find ONE line of code, but in some cases I need to find a whole block.
Well, show us that code and we can work from that on. As far as string searching goes, a new line is just one or two characters - \n, or \r, or \r\n or \n\r.

The code is strange. It looks like either you're implementing a database on top of a database, or it's a clever hack built on "DESCRIBE table" to autogenerate SQL. Either way it's not what I would call a good code, at least "dress" it up in a function API of sorts.
milton_1223
Forum Newbie
Posts: 4
Joined: Wed Apr 30, 2008 7:21 pm

Re: Find and Replace PHP Code in an Existing File

Post by milton_1223 »

No, Mordred, that code above is not the code Im working on, it is just an example of the code to search and replace. Lets say that inside a function you have a statement or a procedure that you want to modify, then search for it and replace it with another statement or procedure. That´s what Im trying to do. But any how this is what I´ve got so far...

Code: Select all

 
$file = "x_file.php";
 
$search_string = preg_quote('$userinfo[\'ship_country_list\'] = getoptionlist(\'state_country\', \'abb\', \'name\', \'WHERE type=\'\' . COUNTRY . \'\'\', ($userinfo[ship_country] == "") ? $settings[country] : $userinfo[ship_country], \'name\');');
 
$file_string = file_get_contents($file);
 
searchFileData($file_string, $search_string);
 
function searchFileData($file_string, $search_string){
 
      $found = preg_match('/('.$search_string.')/', $file_string);
      $foundStr = "Found in $found places";
      echo "<br>" . $foundStr . "<br>";
}
 
Ok now, first of all I know it is not pretty, but it´s just a star. So far this finds me the string in the file if it is only one line, but how do I find multiple consecutive lines (a block of code).
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Re: Find and Replace PHP Code in an Existing File

Post by Mordred »

Good, you're on the right track.
Try this for direct search and replace in the code: preg_replace()
Try replacing "new lines" in your matching blocks with \n
milton_1223
Forum Newbie
Posts: 4
Joined: Wed Apr 30, 2008 7:21 pm

Re: Find and Replace PHP Code in an Existing File

Post by milton_1223 »

Ok, that´s where I get completely lost. the new line, the carriage return and the tabs, how do I put them into this equation... I know that I have to use preg_replace, Im just using preg_match here cause I want to find the match first... look in the second example of what im trying to do, I want to replace that whole block, how should I assign it to a variable, with or without the tabs, with or without \n and how should I recall it from the function... In the file that Im going to change it appears formatted like that... Im completely lost here...
milton_1223
Forum Newbie
Posts: 4
Joined: Wed Apr 30, 2008 7:21 pm

Re: Find and Replace PHP Code in an Existing File

Post by milton_1223 »

Ok, here is the solution I came up with... Althoug it may not be perfect, it works for me, and it may be a start for something far more complex and functiona...

First of all forget abot regex and that stuff, Is too complex for me... at least for now, I want to learn that soon but dont have the time now...

Here goes... First define my imput and output file, since im replacing its just one.

Code: Select all

 
<?php
$file = "x_file_x.php";
 
Then, i define an array with the lines of code that I want to search for

Code: Select all

 
$search[0] ="\t\t".'$userinfo[\'ship_country_list\'] = getoptionlist(\'state_country\', \'abb\', \'name\', \'WHERE type=\\\'\' . COUNTRY . \'\\\'\', ($userinfo[ship_country] == "") ? $settings[country] : $userinfo[ship_country], \'name\');'."\r\n";
$search[1] ="\t\t".'if ($_POST[\'do\'] == "create" && !$ae->is_errors())'."\r\n";
$search[2] ="\t\t\t\t\t\t".'while ($field = $DB_site->fetch_assoc($result))'."\r\n";
$search[3] ="\t\t\t\t".'return template(\'account_customer_signup.html\', array(\'userinfo\' => $userinfo, \'hide\' => $hide, \'lang\' => $lang[account], \'message\' => array(\'error\' => $ae->display())));'."\r\n";
$search[4] ="\t\t".'if (p($settings[order_min]) != p(0) && p($orderinfo[total], false) < p($settings[order_min], false))'."\r\n";
 
After that define arrays with the replacements codes that Im going to use...

Code: Select all

 
 
 
$replace_01[0]="\t\t".'////////////// End Account Type - Changes Required/////////////'."\r\n";
$replace_01[1]="\t\t".'$userinfo[\'account_type_list\'] = getoptionlist(\'groups\', \'id\', \'name\', \'WHERE visible=\\\'1\\\' \', $userinfo[group_in], \'name\', 1);'."\r\n";
$replace_01[2]="\t\t".'$userinfo[\'account_type\'] = getaccounttype($userinfo[group_in]);'."\r\n";
$replace_01[3]="\t\t".'////////////// Start Account Type - Changes Required/////////////'."\r\n";
 
$replace_02[0]="\t\t".'////////////// End Account Type - Changes Required/////////////'."\r\n";
$replace_02[1]="\t\t".'}'."\r\n";
$replace_02[2]="\t\t".'    }'."\r\n";
$replace_02[3]="\t\t".'        }'."\r\n";
$replace_02[...    and so forth....
 
Notice that for each search line that we defined in the $search array there should be a corresponding $replace_xx array

Ok now lets define our function...

Code: Select all

 
function find_and_replace($far, $search, $file, $replace, $line_shift)
{
// $far case values: 1=Find, 2=Add, 3=Replace
    $subject = file($file);
    $first_appearance = array_search($search,$subject);
    $keys = array_keys($subject,$search);
    switch ($far) {
        case 1: //Search
            echo "Match found ".count($keys)." times." ;
            return;
        case 2: //Add
            // $lineshift = amount of lines to move the insertion point
            $temp_array = array_slice($subject, $first_appearance+$line_shift);
            foreach ($replace as $v) array_unshift($temp_array,$v);
            array_splice($subject, $first_appearance+$line_shift, count($subject), $temp_array);
            file_put_contents($file, $subject);
            echo "Code Successfully Added.<br>";
            break;
        case 3:  //Replace
            // $lineshift = amount of lines to replace
            $temp_array = array_slice($subject, $first_appearance);
            $temp_array = array_slice($temp_array, $line_shift);
            foreach ($replace as $v) array_unshift($temp_array,$v);
            array_splice($subject, $first_appearance, count($subject), $temp_array);
            file_put_contents($file, $subject);
            echo "Code Successfully Replaced.<br>";
            break;
    }
}
 
I think it is pretty self explanatory...

Ok this is the line tha calls the function...

Code: Select all

 
find_and_replace(2,$search[1],$file,$replace_01, -3);
 
The parameters are as follow:
  • $far --> Parameter to determine the action (1=search, 2=add or 3=replace).
  • $search --> The string to search for.
  • $file --> The file to work with.
  • $replace --> The replacement or add text.
  • $line_shift --> If it´s addin text this is the amount of lines to move the insertion point (+=down, -=up), but if it´s replacing then this is the amount of lines to replace.
This way although it maight not be pretty, I can work arround what´s posted on the first post. Any suggestions on how to make it better... Thanks to all who helped me... Im not a programmer, this is just a hobby for me, Im actually a Doctor... So if anyone has a medical issue I might be able to help...
Post Reply