Reputation: 1517
The aim is to remove all starting and ending \n
from a string. There can be none, one and many \n
at the start and end, independently in number.
I thought on using preg_replace
with a regex expression. But the following test is not working:
$text = "asd\nasd\nasd\nasd\n";
//$text = "\n\nasd\nasd\nasd\nasd\n";
$text = preg_replace('/^(\\n)*(?!\\n)(.*)(?<!\\n)(\\n)*$/', '$2', $text);
var_dump($text);
With regex101.com the group 2 (see $2
above) is exactly the middle of the string, without starting and ending \n
.
Questions:
/^(\\n)*(.*)(\\n)*$/
instead of the one given above, do I have any disadvantage? In the regex expression above I try "start with \n - any char except \n - any char wanted but not end with \n - end with \n". And in the shorter expression I just list none, one or many \n at start and end. But could this be a problem, that e.g. only one of many \n
at start/end will be replaced and some will not be replaced? Is there a guarantee, that a \n
will not be part of the (.*)
in the middle?EDIT with solution
trim
function. (In my case the preg_replace
had a special reason, so for me this answer from ryszard-czech worked)$text
must be with double quotes "
and not with single quotes '
because there is a significant difference in PHP!Upvotes: 1
Views: 351
Reputation: 18611
Use
$text = preg_replace('/^\n+|\n+\z/', '', $text);
Explanation
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
\n+ '\n' (newline) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\n+ '\n' (newline) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
\z the end of the string
Upvotes: 1