删除PHP文本文件中未知的内容


Remove unknown contents of a text file in PHP

有没有办法在PHP中删除文本文件的内容(子字符串)

我知道要删除的字符串的开始和结束,但不知道内容

之间的所有内容

文件(routes.php)我想编辑

I want to keep this text here
# [[[@-100] I also want to remove the comment line here
  I want to remove this text here
# I also want to remove this line  [@-100]]]
I want to keep this line too

我想删除以# [[[@-100]开始以[@-100]]]结束的内容块

我使用codeignighter,所以我写我的文件像这样

$ROUTE_FILE ='system/routes.php'
$output = file_get_contents($ROUTE_FILE);
$output = $output->remove_substring(...);
$this->write_file($ROUTE_FILE, $output);

已测试:

$mystring='this is # [[[@-100] not [@-100]]] this string you want';
echo remove_substring('# [[[@-100]','[@-100]]]',$mystring);
function remove_substring($head,$foot,$string){
    $top=reset(explode($head,$string));
    $bottom=end(explode($foot,$string));
    return $top.$bottom;
}
输出:

这是你想要的字符串

这是一个不返回错误的版本:

测试:

$mystring='this is # [[[@-100] not [@-100]]] this string you want';
echo remove_substring('# [[[@-100]','[@-100]]]',$mystring);
function remove_substring($head,$foot,$string){
    $top=explode($head,$string);
    $top=reset($top);
    $bottom=explode($foot,$string);
    $bottom=end($bottom);
    return $top.$bottom;
}

  • 用' (?s)
  • 激活DOTALL模式
  • 转义[braces],这样引擎就不会将它们混淆为字符集
  • 使用.*?匹配分隔符之间的所有内容。

php代码:

$replaced = preg_replace('~(?s)# '['['[@-100'] Start of custom routes.*?# End of custom routes '[@-100']']']~',
                         '', $yourinput);

查看这个演示底部的输出