9951 explained code solutions for 126 technologies


php-regexHow to use PHP regex to match a nbsp HTML whitespace?


PHP regex can be used to match a nbsp HTML whitespace by using the \s character class. This character class matches any whitespace character, including the nbsp HTML whitespace.

$string = 'This is a string with a nbsp whitespace.';

if (preg_match_all('/(\s+| +)/', $string)) {
    echo 'Matched whitespace!';
}

Output example

Matched whitespace!

Code explanation

  • \s+| +: character class that matches any whitespace character, including the nbsp HTML whitespace
  • preg_match(): PHP function that searches a string for a pattern, and returns true if the pattern exists, and false otherwise

Helpful links

Edit this code on GitHub