Back to results for “JSON”
PHP › Regular Expressions in PHP

When should a developer prefer using a dedicated parser or a simpler string function over a complex regular expression, particularly for structured formats like HTML or JSON?

Advanced

Answer

While regular expressions are powerful for matching relatively simple, well defined text patterns, they are generally a poor choice for reliably parsing complex, deeply nested structured formats like HTML or JSON, since these formats have recursive, context sensitive grammar rules that regular expressions are fundamentally not well suited to correctly handle, meaning a dedicated parser, such as PHP's built in JSON functions or a proper HTML parsing library, will almost always be more reliable, maintainable, and correct than attempting to hand craft an equivalent regular expression.
// Fragile and error prone
// preg_match('/<title>(.*)<\/title>/', $html, $matches);

// Reliable: use a proper HTML parser
$dom = new DOMDocument();
$dom->loadHTML($html);
$title = $dom->getElementsByTagName('title')->item(0)->textContent;
Real-world example A developer initially attempts to extract data from an HTML page using a hand written regular expression, but after encountering repeated edge case failures with slightly different HTML formatting, switches to using PHP's built in DOMDocument class for reliable, correct HTML parsing instead.

Common follow-ups: What specific characteristics of HTML and JSON make them fundamentally difficult to reliably parse with regular expressions?;What built in PHP tools are available for properly parsing HTML and XML documents?