Search code examples
phppreg-replacewordsremoving-whitespace

PHP Code Snippet - Preg Replace to ensure only 1 whitespace between words in a string


I am using preg_replace to strip unwanted characters from a string. Thats working fine.

What i would to additionally have is just to modify that ( or in the next line ) so that i can allow max 1 whitespace in between words. No whitespace in front or behind the string.

I have seen the reply at PHP preg_match needed to ensure only ONE space character is allowed between words where a possible solution was posted ( solution -> ^[a-zA-Z]+( [a-zA-Z]+)*$) but with some questions raised ( what is the definition of the word? what type of whitespace )

My Word definition -> english words ( including a-z,A-Z,0-9,- , _ )

Whitespace -> spacebar whitespace ( &nbsp) , not newlines,etc

Any code snippets?

Thanx, Meswara


Solution

  • Try this:

    <?php
    $my_str = 'Hello,    too  many      spaces!';
    $my_str = preg_replace('#[\s]+#', ' ', $my_str);
    echo $my_str; // returns 'Hello, too many spaces!'