How can I use regex to remove a line from a file with PHP? -


i writing extension codeigniter's language class remove language line file. script provided array key determine file line remove. don't believe have written regex detect config file line. here cat_names language file:

<?php  $lang['cat_123'] = 'transportation'; $lang['cat_124'] = 'restaurants'; 

this language class extension:

public function remove_line($line, $file){      $ci =& get_instance();     $ci->load->helper('file');      foreach($this->existing_langs $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 following call method removes lines language file:

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

why isn't preg_replace removing lines? note: language file not read-only.

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

your regex doesn't work because:

  • $lang in double quoted string interpreted variable (also, variable doesn't exist);
  • you missing single quotes ' inside square brackets;
  • $line, variable, escaped.

change in way:

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

also note = not need escaped , way escape $ followed characters.

in addition, suggest use single-quoted string , set delimiters character (in regular expressions ^ means begin of line. here works, can confusing).

this single-quote equivalent different delimiters:

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

eval.in demo


Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -