PHP preg_replace to also remove line breaks
Ok, reading a file using file_get_contents
and removing <?php
, <?
, and/or any ?>
tags, but I also want to remove all line breaks within the file. How can I achieve this?
For example a file like so:
<?php
$txt['dpmod_testing'] = 'Testing';
$txt['dpmodtitle_testing'] = 'My Testing Module';
$txt['dpmodinfo_testing'] = 'Just a Testing Module, nothing special.';
$txt['dpmoddesc_testing'] = 'Here is a description for this testing module that you will see within the Add Modules section![color=red]I can give myself credit for this module if I want to![/color][hr]And this text string also accepts BBC Code!';
?>
Should return this:
$txt['dpmod_testing'] = 'Testing';
$txt['dpmodtitle_testing'] = 'My Testing Module';
$txt['dpmodinfo_testing'] = 'Just a Testing Module, nothing special.';
$txt['dpmoddesc_testing'] = 'Here is a description for this testing module that you will see within the A开发者_JAVA技巧dd Modules section![color=red]I can give myself credit for this module if I want to![/color][hr]And this text string also accepts BBC Code!';
But instead I am getting this written to the file, when using file_put_contents
:
$txt['dpmod_testing'] = 'Testing';
$txt['dpmodtitle_testing'] = 'My Testing Module';
$txt['dpmodinfo_testing'] = 'Just a Testing Module, nothing special.';
$txt['dpmoddesc_testing'] = 'Here is a description for this testing module that you will see within the Add Modules section![color=red]I can give myself credit for this module if I want to![/color][hr]And this text string also accepts BBC Code!';
With 2 line breaks above and 2 line breaks also below. How can I remove all of these line breaks?
Here is the preg_replace I am using to remove the php tags from within the file, but how can this be modified to also keep the file the way it is, and remove all line breaks?
preg_replace(array('/<\?php/s', '/\?>/s', '/<\?/s'), array('', '', ''), $str);
Thanks guys :)
like written in
Removing redundant line breaks with regular expressions
you could probably add '(?:(?:\r\n|\r|\n)\s*){2}/s' and '' to your arrays ..but I did not check
just make sure ich matches new line twice only
This seems to be the simplest solution; works perfectly for me with PHP:
http://php.net/manual/en/function.preg-replace.php#85883
Basically you add "(*ANYCRLF)" to the beginning of your regex selection pattern. Supported since PCRE version 7.3
More detailed explanation here:
http://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions
("Newline/linebreak options" section)
Better would be:
$content = file_get_contents('file.php');
$content = trim($content);
$content = ltrim($content, '<?php');
$content = ltrim($content, '<?');
$content = rtrim($content, '?>');
$content = trim($content);
file_put_contents('file.php', $content);
精彩评论