How do I use preg_match to test for spaces?

How do I use preg_match to test for spaces?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Use preg_match to Detect Spaces in PHP Strings

When validating user input or processing text streams, determining whether a string contains whitespace is a common requirement. While PHP offers simple functions like str_contains() for exact matches or preg_match_all() for counting occurrences, using preg_match() with a specific regex pattern is the idiomatic approach when you need to verify existence rather than extract data.

To test if a string contains any space character, you must construct a regular expression that targets the whitespace token. The most robust solution utilizes the \s escape sequence within a character class or directly in a quantified group. However, for a strict binary check of the space character specifically (U+0020), the pattern /\s/ is generally sufficient because it matches spaces, tabs, newlines, and other Unicode whitespace characters, which usually satisfies the broader definition of "spaces" in text processing contexts.

Here is the fundamental implementation using a positive lookahead assertion or a simple existence check:

$string = 'this sentence would be tested true for spaces';

// Check if the string contains at least one whitespace character
if (preg_match('/\s/', $string)) {
    echo "Spaces detected.";
} else {
    echo "No spaces found.";
}

In this example, preg_match() returns 1 on success, meaning the pattern was found. If you need to strictly test for the specific ASCII space character (0x20) and ignore tabs or newlines, you should adjust the pattern to / /./. Note that in regex syntax, a literal space inside square brackets [ ] requires escaping: /\s/ is preferred for general whitespace detection because it handles edge cases like non-breaking spaces often found in copied text.

The source material provided illustrates two distinct scenarios. The first string, "this sentence would be tested true for spaces", contains multiple instances of the space character between words. When passed through preg_match('/\s/', $string), the function stops scanning immediately after finding the first match and returns a truthy value. Conversely, the second example, "thisOneWouldTestFalse", consists entirely of alphanumeric characters with no delimiters. The regex engine scans the entire buffer without finding a match, returning 0.

A critical consideration when using preg_match() for this purpose is performance on very large strings. While the function is optimized in C, calling it repeatedly inside tight loops or high-throughput APIs can introduce latency compared to native string functions like str_contains(' ', $string). However, regex offers pattern flexibility. If your requirement expands beyond a simple space—for instance, checking for any whitespace including tabs, newlines, or carriage returns—the \s quantifier becomes necessary as standard str_contains() checks are literal and do not inherently cover all Unicode whitespace categories without additional logic.

Another pitfall involves the difference between "any whitespace" and "space character." In many natural language processing tasks, a tab character counts as a space. If your application treats tabs as valid delimiters, /\s/ is the correct choice. If you must strictly reject tabs but accept spaces, you would need / /./. This distinction matters when cleaning up URLs or parsing fixed-width fields where tabs might be accidental artifacts rather than intended separators.

For Laravel developers working with Eloquent forms or validation rules, integrating this logic often happens within a custom validator rule. You can create a method that utilizes preg_match() to ensure input adheres to specific spacing requirements before saving to the database. This ensures data integrity at the application layer regardless of how the string was originally formatted.

Ultimately, preg_match() is the right tool when you need the power of pattern matching to decide on boolean outcomes involving whitespace. It bridges the gap between simple character checks and complex parsing needs without requiring external libraries or verbose conditional logic.

Our network