How to match whitespace, carriage return and line feed using regular expression in PHP?

In PHP, you can match whitespace, carriage return, and line feed using the following regular expression:

<?php
$regex = '/[\s\r\n]+/';
$string = "This is a string\nwith multiple\r\nline breaks.";
$split = preg_split($regex, $string);
foreach ($split as $line) {
  echo $line . PHP_EOL;
}

The square brackets [] indicate a character set, and the characters inside the brackets are the characters that will be matched. The \s character class matches any whitespace character, including space, tab, and newline. The \r and \n are the actual characters for the carriage return and line feed.

Watch a course Learn object oriented PHP

You can use this regular expression with any of the PHP functions that work with regular expressions, such as preg_match(), preg_replace(), or preg_split().

For example, if you want to replace all the whitespace, carriage return and line feed with an underscore in a string, you could use the following code:

<?php
$regex = '/[\s\r\n]+/';
$string = "This is a string\nwith multiple\r\nline breaks.";
$new_string = preg_replace($regex, '_', $string);
echo $new_string;

It would replace all the whitespaces, cr and lf with an underscore in the string.