skip to Main Content

an external program generates a file for me like this:

"lorem ipsum",

"lorem ipsum",
"lorem ipsum",

"lorem ipsum"

and I want to obtain:

"lorem ipsum",
"lorem ipsum",
"lorem ipsum",
"lorem ipsum"

I would like to remove these free spaces made by creating a new line, I was thinking about regex but I have no idea how to do it.

I tried regex but didn’t find query

2

Answers


  1. In PHP function preg_replace is used for replacing by regex. Actual regex is based matching multiple consecutive new line (n) by single one.

    <?php
    $str = '"lorem ipsum",
    
    "lorem ipsum",
    "lorem ipsum",
    
    "lorem ipsum"
    ';
    
    echo("<pre>" . preg_replace('/n+/', "n", $str) . "</pre>");
    
    Login or Signup to reply.
  2. The idea: match all white-space sequence greedily and let the regex engine backtrack if needed until an end of line.

    $str = '
    "lorem ipsum",
    
    "lorem ipsum",
    "lorem ipsum",
    
    "lorem ipsum"
    ';
    
    $str = preg_replace('~s+$~mu', '', $str);
    
    echo $str;
    

    Pro:

    • It works with any newline sequence and do not change it.
    • It removes as well trailing blank lines
    • It removes also blank lines that eventually contains a space or any other white character.

    Cons:

    • It right-trims each line, that may be an unwanted behavior.
    • It removes leading blank lines except one. So an additional step is needed to trim it. (eventually the pattern can be changed to ~As*R|s+$~mu)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search