I'm trying to remove extra lines between the texts and here is what I tried:
<?php
echo preg_replace("/^\s /", "\n", $_POST["description"]);
The input:
The output:
I tried the same regular expression on
As you can see nothing changed when I executed the regular expression using PHP, But it is working as what I want when using the regex101 website.
The current PHP version is 7.4.28.
Did I miss something?
CodePudding user response:
You may use this preg_replace
code that would not require m
mode:
echo preg_replace('/(?:\h*\R){2,}/', "\n", $_POST["description"]);
Here (?:\h*\R){2,}
has a non-capture group that will match 0 or more horizontal whitespaces followed by any kind of line break. This non-capture group is repeated 2 or more times.
Please note that it will also remove trailing and leading whitespaces in addition to stripping multiple line breaks into one.
Alternatively using your own approach it would be:
echo preg_replace('/^\s /m', "\n", $_POST["description"]);
Note that would require m
or MULTILINE
mode.
CodePudding user response:
The problem is that normally ^\s
refers to the very start of the string, and not to the start of each line, unless you run the regex in multiline mode. But I think you really want this logic instead:
echo preg_replace("/\n{2,}/", "\n", $_POST["description"]);
This just replaces 2 or more newlines with a single newline.