Detect HTML tags in a string

Detect HTML tags in a string

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

Stefan Bogdanescu

Founder & Senior Architect

Fixing the Regex Error and Exploring Alternatives for HTML Tag Detection

The error Unknown modifier '\' in your preg_match call stems from a misunderstanding of how PHP processes escape sequences within double-quoted strings versus single-quoted strings, combined with the specific syntax required for lookbehind assertions. In your provided code snippet:

if(!preg_match('(?<=&lt;)\w+(?=[^&lt;]*?>)', $string)){ 
    return $string;
}

You are attempting to use a Perl-compatible Regular Expression (PCRE) lookbehind (?<=...). However, inside the pattern string, you have escaped the less-than sign using HTML entities (&lt;) and then wrapped that in backslashes for regex escaping. The specific issue causing the "Unknown modifier" error is usually tied to how PHP interprets the backslash at the start of the lookbehind or within the character class when mixed with HTML entity decoding logic, but the most immediate culprit here is likely the context of string parsing.

More critically, your pattern logic attempts to match a literal < by using &lt;. If you are passing a raw string (e.g., "<div>") into this function, PHP does not automatically decode HTML entities like &lt; back into < inside the subject of preg_match. Therefore, you are trying to match the text &lt; against your input. If your input actually contains the character <, your regex will fail to find it because it is looking for the literal string &lt;.

The Correct Regex Approach

If you decide to stick with a regular expression, you must first ensure you are matching the actual ASCII characters (< and >) rather than their HTML entity representations. Furthermore, PHP's lookbehind assertions have strict requirements regarding what can be inside them. In older versions of PHP (prior to 7.3), lookbehinds had to be fixed-width. While modern PHP handles variable-width lookbehinds well, the syntax must be precise.

A robust regex to detect if a string contains HTML tags looks like this:

$pattern = '/<[^>]+>/';
if (preg_match($pattern, $string)) {
    // Tags found
} else {
    // No tags found
}

This approach uses a simple character class [^>]+ to match anything between the opening and closing brackets. It avoids the complexity of lookbehinds entirely, which is often unnecessary for this specific task. If you strictly need to isolate the tag content or handle self-closing tags like <img />, you might extend the pattern to /<[\/]?\w+[^\s>]*(?:[^>]*<\/\w+>)?>/.

However, if your original intent was to use lookbehinds to ensure a tag exists without capturing the surrounding text, the syntax (?<=<)[^>]+(?=>) works in modern PHP environments. The key takeaway is that you do not need to escape the < and > characters with backslashes inside the character class unless you are specifically looking for the literal string &lt;.

Why Not Regex?

While regex can work, it is often the wrong tool for parsing HTML. HTML is a hierarchical language with nested structures that regular expressions struggle to handle gracefully. For example, attribute values can contain quotes of different types, or they might be missing entirely. A regex designed to match <div class="foo" id="bar"> will likely fail if it encounters <div class='foo' id='bar'>.

For production applications where HTML integrity is critical, using a DOM parser is the standard best practice. Libraries like DOMDocument or SimpleXML allow you to iterate through nodes safely without worrying about edge cases that break regex patterns.

A Laravel-Specific Solution

If you are working within the Laravel ecosystem, you can leverage existing packages or built-in utilities to simplify this check. While Laravel does not include a dedicated "HTML tag detector" core helper, the community often provides robust tools for sanitizing and validating HTML content.

For instance, if your goal is to detect tags to sanitize user input before storing it in the database, you might look at packages that extend the functionality of Illuminate\Support\Str. A common pattern in Laravel involves using a sanitizer library like mews/purifier which handles complex HTML validation much better than manual regex checks.

If you are building a utility specifically for this, you can create a simple helper method within your application:

use Illuminate\Support\Str;

function containsHtmlTags(string $string): bool
{
    return Str::contains($string, '<');
}

This uses Laravel's Str facade to perform a fast substring check. If you need to ensure the < is followed by a >, you can combine this with a simple regex or DOM parsing logic depending on your strictness requirements. This approach avoids the overhead of loading a full parser if you only need a boolean flag, while remaining safer than relying solely on complex regex patterns.

Final Considerations

When choosing between regex and parsers, remember that performance is rarely the bottleneck for a single string check in PHP unless you are processing millions of requests per second. The primary trade-off is correctness. Regex is concise but fragile; parsers are verbose but reliable. If your application deals with user-generated content, err on the side of using a parser or a dedicated library to prevent breaking on malformed HTML.

For further reading on string manipulation and validation within the Laravel framework, you can explore resources like https://laravelcompany.com which often discusses best practices for handling input sanitization.

Our network