Optional Whitespace Regex

Optional Whitespace Regex

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

Stefan Bogdanescu

Founder & Senior Architect

Optional Whitespace Regex

Matching HTML attributes often trips up developers because real-world markup rarely adheres to strict formatting rules. While a textbook example might look like <img src="x" width="100" height="100">, production data frequently omits spaces between attributes, as seen in <img src="x"width="100"height="100">. The standard regex approach using [\s*] or [ \t]* often fails when the parser expects a consistent delimiter, causing matches to break on valid HTML that simply lacks spacing.

The core issue lies in how character classes interact with the specific string you are trying to match. In your original pattern, you used src="..." width="150" height="...". If you attempt to make the space optional by changing it to src="..."\s*?\s*width="150", the regex engine becomes ambiguous about whether it is looking for a space before the attribute name or just skipping characters.

A more robust solution involves defining a flexible whitespace block that explicitly allows for either a space, a tab, or nothing at all between attributes. In PHP's preg_match, you can achieve this by replacing the strict space delimiter with [ \t]*. This character class matches zero or more spaces or tabs. By placing this block before every attribute name except the first one, you create a parser that is agnostic to spacing inconsistencies.

Consider modifying your pattern to explicitly handle the transition between the src attribute and the width attribute, and then between width and height. Instead of relying on a single wildcard or a specific space character, define a block that accepts any amount of whitespace, including none:

// Match src, then optional whitespace, then width="150", then optional whitespace, then height
preg_match('#<img alt="(.*?)" src="(.*?)"\s*width="150"\s*height="(.*?)">#', $data, $imagematch);
$image = $imagematch[3]; // Adjust index based on your capture groups

In this revised pattern, \s* is the critical component. It matches zero or more whitespace characters. When the HTML contains a space (e.g., src="..." width), the regex consumes it. When there is no space (e.g., src="..."width), the regex matches zero occurrences of whitespace and proceeds immediately to match the width attribute name. This effectively bridges the gap between rigid formatting expectations and messy reality.

However, you must be careful about the order of operations in your character classes. Using [ \t]* is generally safer than relying on \s alone if you want to strictly control what constitutes valid whitespace, though \s* usually suffices for this specific use case. The trade-off here is performance versus flexibility. Adding multiple optional whitespace blocks increases the complexity of the pattern slightly, but given that HTML parsing is inherently expensive due to the potential size of $data, the slight overhead of a more complex regex is negligible compared to the alternative of writing a full DOM parser or failing to match valid images entirely.

Another consideration is the attribute order. Your original code assumed width always came before height. If your source data sometimes flips this order, such as <img ... height="100" width="150">, a static regex will fail. To handle dynamic attribute ordering, you would need to switch to a non-capturing group that matches any attribute name after the initial src until you hit the closing tag. This transforms the approach from a simple "find text" task into a stateful parsing problem.

If your application is built on Laravel and you are dealing with large volumes of HTML data, consider using the Symfony DomCrawler component or Laravel's built-in string helpers for more complex extraction tasks. While regex is excellent for quick pattern matching like this, it struggles when attribute order varies or when attributes are nested within complex structures. For instance, if you find yourself needing to match alt, src, width, and height in any arbitrary order without caring about the sequence, a single regex becomes unwieldy quickly.

In summary, the fix for ignoring whitespace is to replace the rigid space requirement with \s* or [ \t]* between attribute names. This small adjustment allows your pattern to gracefully handle both <img src="x" width="100"> and <img src="x"width="100"> without requiring two separate regex patterns or maintaining a list of possible spacing variations.

Our network