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 regex101 and here is the result:
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?
2
Answers
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:This just replaces 2 or more newlines with a single newline.
You may use this
preg_replace
code that would not requirem
mode:RegEx Demo
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:
Note that would require
m
orMULTILINE
mode.RegEx Demo