有没有办法在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);
答案 0 :(得分:1)
$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;
}
答案 1 :(得分:1)
DOTALL
模式
[braces]
,以便引擎不会将它们混淆为字符chass .*?
匹配分隔符之间的所有内容。在php代码中:
$replaced = preg_replace('~(?s)# \[\[\[@-100\] Start of custom routes.*?# End of custom routes \[@-100\]\]\]~',
'', $yourinput);
请参阅this demo底部的输出。