Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP make sure string has no whitespace?
To check whether a string contains whitespace in PHP, you can use the preg_match() function with a regular expression pattern. This method detects any whitespace characters including spaces, tabs, and newlines.
Syntax
preg_match('/\s/', $yourVariableName);
Example − Checking for Whitespace
The following example demonstrates how to check if a string contains whitespace ?
<?php
$name = "John Smith";
if (preg_match('/\s/', $name)) {
echo "The name ($name) has whitespace";
} else {
echo "The name ($name) has no whitespace";
}
?>
The name (John Smith) has whitespace
Example − String Without Whitespace
Here's an example with a string that contains no whitespace ?
<?php
$username = "JohnSmith";
if (preg_match('/\s/', $username)) {
echo "The username ($username) has whitespace";
} else {
echo "The username ($username) has no whitespace";
}
?>
The username (JohnSmith) has no whitespace
Alternative Methods
You can also use other approaches to check for whitespace ?
<?php
$text = "Hello World";
// Method 1: Using ctype_space() for strings with only whitespace
if (ctype_space($text)) {
echo "String contains only whitespace";
}
// Method 2: Comparing with trimmed version
if ($text !== trim($text)) {
echo "String has leading or trailing whitespace";
}
// Method 3: Using strpos() to find space
if (strpos($text, ' ') !== false) {
echo "String contains spaces";
}
?>
String has leading or trailing whitespace String contains spaces
Conclusion
The preg_match('/\s/', $string) function is the most reliable method to detect any whitespace in a string. It returns 1 if whitespace is found, 0 if not found.
Advertisements
