Search code examples
phpregexpreg-replacespacescarriage-return

Remove more than two returns and more than one space within php string


I manage to remove the spaces but I can't understand why it would remove my returns as well. I have a textarea in my form and I want to allow up to two returns maximum. Here is what I have been using so far.

$string = preg_replace('/\s\s+/', ' ', $string); // supposed to remove more than one consecutive space - but also deletes my returns ...
$string = preg_replace('/\n\n\n+/', '\n\n', $string); // using this one by itself does not do as expected and removes all returns ...

It seems first line already gets rid of more than one spaces AND all returns ... Which is strange. Not sure than I am doing it right ...


Solution

  • For those of you who will need it, that's how you remove two carriage returns from a textarea.

    preg_replace('/\n\r(\n\r)+/', "\n\r", $str);
    

    For the space issue, as it has been posted above, replace \s by \h