douweng7083 2016-02-27 00:26
浏览 94
已采纳

如何使用正则表达式从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.

  • 写回答

1条回答 默认 最新

  • doushi1960 2016-02-27 00:44
    关注
    "^$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.'\'\] = (.*?)
    /'
    

    <kbd>eval.in demo</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题