Duleep
Duleep

Reputation: 587

how to replace line of string in php file?

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

Upvotes: 0

Views: 182

Answers (2)

The Alpha
The Alpha

Reputation: 146191

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));
}

Upvotes: 1

user2533777
user2533777

Reputation:

$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!!

Upvotes: 0

Related Questions