PHP make sure string has no whitespace?


To check whether a string has no whitespace, use the preg_match() in PHP.

The syntax is as follows 

preg_match('/\s/',$yourVariableName);

Example

The PHP code is as follows

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
$name="John Smith";
if ( preg_match('/\s/',$name) ){
   echo "The name (",$name,") has the space";
} else {
   echo "The Name (",$name,") has not the space";
}
?>
</body>
</html>

Output

This will produce the following output

The name (John Smith) has the space

Updated on: 13-Oct-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements