skip to Main Content

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:

enter image description here

The output:

enter image description here

I tried the same regular expression on regex101 and here is the result:

enter image description here

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


  1. 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.

    Login or Signup to reply.
  2. You may use this preg_replace code that would not require m mode:

    echo preg_replace('/(?:h*R){2,}/', "n", $_POST["description"]);
    

    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:

    echo preg_replace('/^s+/m', "n", $_POST["description"]);
    

    Note that would require m or MULTILINE mode.

    RegEx Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search