How to detect empty space in PHP?

How can I detect all empty spaces in a string that are the result of entering more than one space.

In other words, I do not want to detect this:

" "

But nothing more. For instance:

"  ", "   ", etc...
+3
source share
2 answers

You can use regex:

$regex = '~\s{2,}~';
preg_match($regex, $str);

\sincludes space, tabs and newlines. If you want just spaces, you can change $regexto:

$regex = '~ {2,}~';

If you want to remove extra spaces from a string, you can use:

$str = 'hello  there,   world!';

$regex = '~ {2,}~';
$str = preg_replace($regex, ' ', $str);

echo $str;

Outputs:

hello there, world!
+2
source

You can use:

$input = "foo bar  baz   saz";
if(preg_match_all('/\s{2,}/',$input,$matches)) {
    var_dump($matches);
}

Conclusion:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(2) "  "
    [1]=>
    string(3) "   "
  }
}

\s represents a space, which includes space, vertical tab, horizontal tab, reverse carriage, new line, channel form.

If you want to match only regular spaces, you can use a regex:

if(preg_match_all('/ {2,}/',$input,$matches)) {
0
source

Source: https://habr.com/ru/post/1762023/


All Articles