PHP regex – whitespace shorthand (\s) regex examples

PHP regex whitespace shorthand \s can be used to match whitespace characters. These are the characters it will match.

Char Dec val Oct val
tab 9 \011
newline 10 \012
form feed 12 \014
carriage return 13 \015
space 32 \040

This is convenient way to remove whitespace or replace multiple whitespaces to single space. Here are some preg_replace examples using whitespace.

preg_replace – remove all whitespaces

<?php
$str = "foo bar\nfoo";
$newstr = preg_replace('/\s/', "", $str, -1, $count);
if ($count > 0) {
  echo "newstr after $count replacement(s):\n$newstr\n";
} else {
  echo "No replacement\n";
}
?>
newstr after 2 replacement(s):
foobarfoo
Env: PHP version 5.5.9 (Linux)

preg_replace – collapse multiple whitespaces to single space

<?php
$str = "foo   bar\n\n\nfoo\nbar";
$newstr = preg_replace('/\s+/', ' ', $str, -1, $count);
if ($count > 0) {
  echo "newstr after $count replacement(s):\n$newstr\n";
} else {
  echo "No replacement\n";
}
?>
newstr after 3 replacement(s):
foo bar foo bar
Env: PHP version 5.5.9 (Linux)
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments