0

I have file(php file) that file inside look like bellow

$php_file_string

//define ( 'name', 'saman' );
   //       define ( 'name', 'saman' );
define ( 'name', 'saman' );
#  define ( 'name', 'saman' );
 /* define ( 'name', 'saman' ); */

i want to replace line un-commented

$search_string :

define ( 'name', 'saman' );

$new_value:

define ( 'name', 'RoX' );

i try using

str_replace($search_string, $new_value, $php_file_string);

this replace all lines(five line inside the file). So above str_replace() is not correctly worked for me. I need something look as bellow result

//define ( 'name', 'saman' );
   //       define ( 'name', 'saman' );
define ( 'name', 'RoX' );
#  define ( 'name', 'saman' );
 /* define ( 'name', 'saman' ); */

please help to me how to replace only un-comented lines in php file

Duleep
  • 569
  • 5
  • 25
  • 49

2 Answers2

1

I assumed that, this is the last line (as you mentioned) in your file that you want to change and you have write permission to that, so, symply this should work

$file = 'path/filename.php';
$lines =file($file);
$lines[count($lines)-1]="define ( 'name', 'RoX' );";
if(is_writable($file))
{
    file_put_contents($file, implode($lines));
}

Result would be :

//define ( 'name', 'saman' );
//       define ( 'name', 'saman' );
#  define ( 'name', 'saman' );
/* define ( 'name', 'saman' ); */
define ( 'name', 'RoX' );

Update : (After the question has been edit)

$file = '../mytests/index.php';
$lines = file($file);
for($i=0; $i < count($lines); $i++)
{
    if(substr($lines[$i], 0, 6) === 'define') {
        $lines[$i] = "define ( 'name', 'RoX' );";
    }
}
if(is_writable($file))
{
    file_put_contents($file, implode($lines));
}
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • sorry for that, in my example last line(need to replace every un-commented line) – Duleep Jul 04 '13 at 06:51
  • 1
    You said only un commented lines and also gave a sample of what you want, so i think the output in my answer matches with your sample, now I'm confused. – The Alpha Jul 04 '13 at 06:54
  • 1
    sorry for my question i did some mistake. now i edited my question. thankx – Duleep Jul 04 '13 at 07:04
0
$u=explode("\n",$php_file_string);//Breaking each line into array
for($i=0;$i<count($u);$i++)
{
if(!substr_count($u[$i],"/*")&&!substr_count($u[$i],"#")&&!substr_count($u[$i],"//"))
//Checking whether line contains any comment or not
$u[$i]=str_replace($search_string, $new_value, $u[$i]);
}
//Now you can use $u as an string array

Try this here we are breaking each line into an array and then checking each line separately for comment if a line is not a comment we replace old value with new one Hope it helps!!