What are the differences between using \s and [:space:] in PHP regular expressions?
Using \s in PHP regular expressions matches any whitespace character, including spaces, tabs, and line breaks. On the other hand, [:space:] is a POSIX character class that matches only spaces. If you specifically need to match spaces and not other whitespace characters, you should use [:space:]. However, if you want to match any whitespace character, including spaces, tabs, and line breaks, then \s should be used.
// Using \s to match any whitespace character
$pattern = '/\s/';
$string = 'Hello World';
if (preg_match($pattern, $string)) {
echo 'Whitespace character found';
} else {
echo 'No whitespace character found';
}
// Using [:space:] to match only spaces
$pattern = '/[[:space:]]/';
$string = 'Hello World';
if (preg_match($pattern, $string)) {
echo 'Space character found';
} else {
echo 'No space character found';
}