如何使用正则表达式从PHP中删除文件中的行?

I am writing an extension to CodeIgniter's language class that will remove a certain language line from a certain file. 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:

<?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\] \= (.*?)\
^", '', $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? Note: the language file is not read-only.

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

Your RegEx doesn't work because:

  • $lang in double quoted string is interpreted as variable (also, this variable doesn't exist);
  • You are missing single quotes ' inside square brackets;
  • $line, which is a variable, is escaped.

Change it in this way:

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

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.'\'\] = (.*?)
/'

eval.in demo