n00b
n00b

Reputation: 16536

PHP Regexp - Remove redundant spaces but keep line breaks

I'm looking for a regular expression that removes redundant (two or more) spaces but keeps line breaks.

Any idea how that would work?

Thanks in Advance!

Upvotes: 2

Views: 3399

Answers (4)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

To replace all horizontal whitespace symbols with a single space in a string, you can use

preg_replace('/\h+/', ' ', $str);

where \h is a PCRE-specific shorthand character class matching all characters that \p{Zs} matches plus U+0009 (a horizontal tab).

The quantifier + after \h enables matching one or more horizontal whitespace symbols. To only match two or more occurrences, use a limiting quantifier:

preg_replace('/\h{2,}/', ' ', $str);

Upvotes: 0

MDI
MDI

Reputation: 177

Removes 2 ore more spaces:

preg_replace("/[ ]{2,}/", " ", $myval);

Upvotes: 3

Toto
Toto

Reputation: 91428

This will replace all "spaces" but newline by a space

$str = "a   bc


d e       f";
$str = preg_replace('/[^\S\n]+/', ' ', $str);
echo $str,"\n";

output:

a bc


d e f

Upvotes: 2

Spliffster
Spliffster

Reputation: 7219

Remove spaces and tabs

preg_replace("/[ \t]+/", " ", $myval);

Remove only spaces

preg_replace("/[ ]+/", " ", $myval);

Upvotes: 8

Related Questions