Reputation: 3790
Is there a way to remove contents (substring) of a text file in PHP.
I know the start and the end of the string to remove, but not everything in between the content
File (routes.php) I want to edit
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
So I want to remove the content block that starts with # [[[@-100]
and ends with [@-100]]]
Im using codeignighter so I write my file like so
$ROUTE_FILE ='system/routes.php'
$output = file_get_contents($ROUTE_FILE);
$output = $output->remove_substring(...);
$this->write_file($ROUTE_FILE, $output);
Upvotes: 0
Views: 89
Reputation: 3729
$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;
}
output:
this is this string you want
Here's a version that does not return errors:
$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;
}
Upvotes: 1
Reputation: 41838
DOTALL
mode with `(?s)[braces]
so the engine doesn't confuse them for a character chass.*?
to match everything between the delimiters.In php code:
$replaced = preg_replace('~(?s)# \[\[\[@-100\] Start of custom routes.*?# End of custom routes \[@-100\]\]\]~',
'', $yourinput);
See the output at the bottom of this demo.
Upvotes: 1