简体   繁体   English

如何替换PHP文件中的字符串行?

[英]how to replace line of string in php file?

I have file(php file) that file inside look like bellow 我有文件(php文件)里面的文件看起来像下面

$php_file_string $ 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 : $ search_string:

define ( 'name', 'saman' );

$new_value: $ 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. 因此,上面的str_replace()对我来说不正确。 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 请帮助我如何仅替换php文件中未输入的行

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));
}
$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!! 在这里尝试一下,我们将每一行分成一个数组,然后单独检查每一行是否有注释,如果某行不是注释,我们用新值替换旧值,希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM