inwebdeveloper

Free Web Resources – inWebdeveloper

PHP: Replacing multiple spaces with a single space

PHP: Replacing multiple spaces with a single space

PHP: Replacing multiple spaces with a single space

I have a problem when doing HTML scraping in PHP, which is a lot of space. So I tried to find a solution, and I found this code.

[php]
$output = preg_replace(‘!\s+!’, ‘ ‘, $input);
OR
$output = preg_replace("~s/[ \t]{2,}/ /g~", " ", $str);
[/php]

From Regular Expression Basic Syntax Reference:
\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

Example:
[php]
<!–?php $str = "asdasd asdasd asdas1\n asda234 4545 54\n 34545 345 34534\n34 345\n"; $results = preg_replace(‘!\s+!’, ‘ ‘, $str); print $results; //Result In: asdasd asdasd asdas1 asda234 4545 54 34545 345 34534 34 345 ?–>
[/php]

Src:
1. http://stackoverflow.com/questions/2368539/php-replacing-multiple-spaces-with-a-single-space
2. http://forums.devshed.com/regex-programming-147/remove-more-than-2-spaces-but-keep-atleast-one-587129.html


Comments are closed.