toddeTV
toddeTV

Reputation: 1517

PHP regex: remove all chars from start and end

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:

  1. What is wrong with my PHP code above? Why can't I replace the full text with only the middle part? Should I really remove start/end and not replacing with the middle part?
  2. When I use the regex expression /^(\\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

  1. solution: this basic example would also be possible to solve with the PHP trim function. (In my case the preg_replace had a special reason, so for me this answer from ryszard-czech worked)
  2. attention: the string $text must be with double quotes " and not with single quotes ' because there is a significant difference in PHP!

Upvotes: 1

Views: 351

Answers (1)

Ryszard Czech
Ryszard Czech

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

Related Questions