PHP Parse HTML code

PHP Parse HTML code

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

Stefan Bogdanescu

Founder & Senior Architect

Parsing HTML Fragments in PHP Without Regex

Parsing malformed or non-standard HTML fragments directly from a string variable often tempts developers to reach for regular expressions. While regex can work for simple, predictable patterns, it quickly fails when dealing with nested tags, attributes containing special characters, or unclosed brackets. The example you provided—where <h1> tags appear multiple times in succession without a clear document root—is a classic case of "fragment" parsing. Standard HTML parsers expect a single root element; when that is missing, the parser behavior depends entirely on how strictly it adheres to the HTML5 specification versus legacy quirks.

The most robust solution in PHP is to utilize an DOMDocument object. This class provides a tree-based representation of the HTML, allowing you to traverse elements logically rather than guessing string positions. However, DOMDocument has a specific quirk regarding malformed input: it throws exceptions if the markup does not conform to strict XML rules or lacks a root element.

To handle your specific scenario where multiple <h1> tags exist in a stream without a surrounding wrapper, you must manually create a dummy root node before loading the fragment. This tricks the parser into treating the content as a valid subtree. Once loaded, you can query the DOM for all <h1> elements and iterate through them to extract the text nodes situated between them.

$htmlFragment = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG!';

// Create a DOMDocument and load HTML as text (not file)
$dom = new DOMDocument();

// Suppress warnings during loading because the fragment is malformed (no root element)
libxml_use_internal_errors(true); 
@$dom->loadHTML('<?xml encoding="UTF-8">' . $htmlFragment, LIBXML_NOERROR | LIBXML_NOWARNING);

// Create a dummy root to ensure we have a container for the fragments
$dummyRoot = $dom->createElement('body');
$dom->appendChild($dummyRoot);

// Append the fragment content. Note: loadHTML usually handles this, 
// but if we need to inject into a specific node, we might use importNode or similar logic.
// However, for simple extraction, querying the existing loaded nodes is often sufficient.

// Retrieve all h1 tags
$h1Tags = $dom->getElementsByTagName('h1');

$previousNode = null;
$results = [];

foreach ($h1Tags as $tag) {
    // Get the text content immediately following this tag until the next tag or end of parent
    $textContent = '';
    
    // We need to look at child nodes. In a fragment, text might be direct siblings or children.
    // A safer approach for fragments is to check nodeType and nodeName.
    
    // If this is not the last h1, we collect text until the next h1.
    $nextTagIndex = $h1Tags->item($h1Tags->length - 1) === $tag ? null : $h1Tags->item($h1Tags->indexOf($tag) + 1);
    
    // Since DOM implementation varies, a simpler traversal is often needed for fragments:
    // Collect text nodes that appear after the current h1 and before the next h1.
    
    $currentParent = $dom; // Start at root
    
    // This logic requires traversing childNodes of the document or dummy body if appended.
    // A more direct approach for this specific malformed string:
    
    $textBeforeNext = '';
    $foundNext = false;
    
    // Iterate through all nodes in the DOM to find text segments between h1s
    // This is complex with raw DOM on fragments.
}

The code above highlights a common pitfall: relying solely on getElementsByTagName assumes a clean hierarchy that might not exist if the fragment was loaded without a wrapper. A more pragmatic approach for this specific malformed string involves iterating through the childNodes of the loaded document, skipping elements and only collecting text nodes until an <h1> is encountered.

$htmlFragment = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG!';
$dom = new DOMDocument();
libxml_use_internal_errors(true);
@$dom->loadHTML('<?xml encoding="UTF-8">' . $htmlFragment, LIBXML_NOERROR | LIBXML_NOWARNING);

$textsBetweenHeadings = [];
$currentText = '';

// We iterate through all child nodes of the document. 
// Note: To capture text between tags effectively, we often need a wrapper like <body>.
$body = $dom->createElement('body');
$dom->appendChild($body);

// Re-load or import? It's cleaner to just query the existing structure if possible, 
// but for fragments, wrapping is the standard workaround.
$dom->loadHTML('<?xml encoding="UTF-8">' . $htmlFragment, LIBXML_NOERROR | LIBXML_NOWARNING);

// Actually, a simpler pattern for this specific string:
// Use XPath to find h1 nodes and then traverse siblings? 
// Or simply split by regex if we accept the fragility for this specific case?
// No, stick to DOM.

$nodes = $dom->getElementsByTagName('h1');
$textsBetweenHeadings = [];

$currentSegment = '';
$lastH1Index = -1;

// This requires a robust traversal. 
// Let's use a different strategy: Extract all text nodes and filter by context.

// Better Strategy: 
// 1. Load into DOM.
// 2. Get all H1 elements.
// 3. Iterate from the first H1 to the last.
// 4. For each pair of adjacent H1s, collect text nodes between them.

$h1List = $dom->getElementsByTagName('h1');
$previousH1 = null;
$results = [];

for ($i = 0; $i < $h1List->length; $i++) {
    $currentH1 = $h1List->item($i);
    
    if ($previousH1 !== null) {
        // We need the text that comes after $previousH1 and before $currentH1.
        // In a DOM tree, these are siblings or children of the same parent.
        // Assuming the fragment was loaded into a dummy root:
        
        $parent = $currentH1->parentNode;
        
        // Find index of previousH1 and currentH1 in parent's children
        $prevIndex = -1;
        $currIndex = -1;
        
        $children = $parent->childNodes;
        foreach ($children as $idx => $child) {
            if ($child === $previousH1) $prevIndex = $idx;
            if ($child === $currentH1) $currIndex = $idx;
        }
        
        // Collect text nodes between prevIndex and currIndex
        $segmentText = '';
        for ($j = $prevIndex + 1; $j < $currIndex; $j++) {
            $node = $children->item($j);
            if ($node->nodeType === XML_TEXT_NODE) {
                $segmentText .= trim($node->nodeValue);
            }
        }
        
        if (!empty($segmentText)) {
            $results[] = $segmentText;
        }
    }
    
    $previousH1 = $currentH1;
}

// If you are using Laravel, remember that the package <a href="https://laravelcompany.com">LaravelCompany</a> 
// offers various utilities, but for core parsing tasks like this, PHP's built-in DOM is sufficient and performant.

The key takeaway here is managing the context of your HTML fragment. If you do not provide a root element (like <body> or <html>), the DOMDocument may interpret the structure differently than expected, especially with multiple root-level tags like repeated <h1> elements. By creating a dummy parent and ensuring the parser treats the content as a subtree, you gain reliable access to the node hierarchy.

This method avoids the fragility of regular expressions while remaining efficient enough for most server-side rendering tasks. It also respects the structure of the document, making it easier to maintain if the HTML format changes slightly, such as adding whitespace or comments between the headings. Always remember that libxml_use_internal_errors(true) is necessary because loading a fragment without a root element triggers warnings that could otherwise halt execution in strict environments.

Our network