简体   繁体   English

如何使用regex使用PHP从文件中删除一行?

[英]How can I use regex to remove a line from a file with PHP?

I am writing an extension to CodeIgniter's language class that will remove a certain language line from a certain file. 我正在编写CodeIgniter语言类的扩展,它将从特定文件中删除特定语言行。 The script is provided an array key to determine which file line to remove. 为脚本提供了一个数组键,以确定要删除的文件行。 I don't believe I have written my regex properly to detect a config file line. 我不相信我已经正确编写了正则表达式来检测配置文件行。 Here is the cat_names language file: 这是cat_names语言文件:

<?php

$lang['cat_123'] = 'Transportation';
$lang['cat_124'] = 'Restaurants';

This is my language class extension: 这是我的语言课扩展:

public function remove_line($line, $file){

    $CI =& get_instance();
    $CI->load->helper('file');

    foreach($this->existing_langs as $lang){

        $lang_contents = read_file($this->lang_path.'/'.$lang.'/'.$file.'_lang.php');

        $new_contents = preg_replace("^$lang\[\$line\] \= (.*?)\\n^", '', $lang_contents);

        write_file($this->lang_path.'/'.$lang.'/'.$file.'_lang.php', 'w+');

    }

}

I use the following to call the method that removes lines from the language file: 我使用以下方法来调用从语言文件中删除行的方法:

$this->lang->remove_line('cat_123', 'cat_names');

Why isn't my preg_replace removing the lines? 为什么我的preg_replace不删除行? Note: the language file is not read-only. 注意:语言文件不是只读的。

"^$lang\[\$line\] \= (.*?)\\n^"
"^\\$"."lang\['$line'\] = (.*?)\n^"

Your RegEx doesn't work because: 您的RegEx无法正常运作,因为:

  • $lang in double quoted string is interpreted as variable (also, this variable doesn't exist); 双引号字符串中的$lang被解释为变量(同样,该变量不存在);
  • You are missing single quotes ' inside square brackets; 你缺少单引号'方括号内;
  • $line , which is a variable, is escaped. $line是一个变量,被转义。

Change it in this way: 以这种方式更改它:

"^\\$"."lang\['$line'\] = (.*?)\n^"

Also note that the = does not need to be escaped and the way to escape $ followed by characters. 还要注意, =不需要转义,转义$的方式后面是字符。

In addition, I suggest you use a single-quoted string and set delimiters to another character (in regular expressions ^ means begin of line. Here it works, but can be confusing). 另外,我建议您使用单引号引起来的字符串,并将定界符设置为另一个字符(在正则表达式中^表示行的开头。在这里可以使用,但可能会造成混淆)。

This is single-quote equivalent with different delimiters: 这是带不同分隔符的单引号等效项:

'/\$lang\[\''.$line.'\'\] = (.*?)\n/'

eval.in demo 评估演示

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

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