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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀