php-regexHow to match a space using PHP regex?
To match a space using PHP regex, you can use the \s
character class. This character class matches any whitespace character, including spaces, tabs, and line breaks.
Example code
$string = 'This is a string with a space.';
$pattern = '/\s/';
if (preg_match($pattern, $string)) {
echo 'A space was found!';
}
Output example
A space was found!
Code explanation
$string
: This is a string variable containing the string to be searched.$pattern
: This is a string variable containing the regular expression pattern to be used for the search. The\s
character class is used to match any whitespace character, including spaces, tabs, and line breaks.preg_match()
: This is a PHP function used to search a string for a pattern. It takes two parameters: the pattern to search for, and the string to search in.echo
: This is a PHP statement used to output a string.
Helpful links
More of Php Regex
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a zip code?
- How to use an "or" condition in PHP regex?
- How to use PHP regex to get a YouTube video ID?
- How to convert a PHP regex to JavaScript regex?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match a year?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match special characters?
See more codes...