How to extract only text from HTML string with PHP?

How to extract only text from HTML string with PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

Stripping HTML Tags in PHP: A Practical Guide

Extracting plain text from an HTML string is a common task when preparing content for meta descriptions, SEO tools, or simple log displays. The goal is straightforward: remove all markup while preserving the whitespace and order of the visible characters. In your specific case, you have a string containing nested tags like <strong>, <a>, and <p>, and you need just the narrative text to fit inside a <meta> tag.

The most naive approach often involves using regular expressions with preg_replace to find and remove patterns matching <...>. While this works for simple cases, it quickly breaks down when dealing with nested tags, attributes containing special characters, or malformed HTML. A regex solution might accidentally strip content inside a comment block or fail to handle self-closing tags correctly.

A more robust strategy leverages PHP's built-in DOM parser. By using DOMDocument and its associated DOMNodeIterator, you can traverse the document tree logically rather than relying on string pattern matching. This ensures that even if the HTML is slightly malformed, the parser attempts to correct it before you extract the text nodes.

Here is a practical implementation using the DOM approach:

$htmlString = '<div class="devblog-index-content battlelog-wordpress">
<p><strong>The celebration of the Recon class in our second </strong><a href="http://blogs.battlefield.com/2014/10/bf4-class-week-recon/" target="_blank">BF4 Class Week</a><strong> continues with a sneaky stroll down memory lane. Learn more about how the Recon has changed in appearance, name and weaponry over the years&amp;hellip;</strong></p>

<p>&nbsp;</p>

<p style="text-align:center"><a href="http://eaassets-a.akamaihd.net/battlelog/prod/954660ddbe53df808c23a0ba948e7971/en_US/blog/wp-content/uploads/2014/10/bf4-history-of-recon-1.jpg?v=1412871863.37"><img alt="bf4-history-of-recon-1" class="aligncenter" src="http://eaassets-a.akamaihd.net/battlelog/prod/954660ddbe53df808c23a0ba948e7971/en_US/blog/wp-content/uploads/2014/10/bf4-history-of-recon-1.jpg?v=1412871863.37" style="width:619px" /></a></p>
</div>';

// Create a DOMDocument instance
$dom = new DOMDocument();

// Load the HTML string. The second parameter (LIBXML_NOERROR | LIBXML_NOWARNING) prevents warnings for malformed HTML.
// You must suppress errors or use these flags to avoid PHP notices from invalid markup.
libxml_use_internal_errors(true);
$dom->loadHTML($htmlString, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();

// Create a text node iterator
$textIterator = new DOMNodeIterator($dom->getElementsByTagName('body')->item(0));

// Iterate through all nodes and append only those that are text nodes or have childTextNodes
$plainText = '';
foreach ($textIterator as $node) {
    if ($node->nodeType === XML_TEXT_NODE) {
        // Get the actual data. trim() handles leading/trailing whitespace of this specific node.
        $plainText .= trim($node->textContent);
    }
}

// Trim final result to remove extra spaces between paragraphs if desired, 
// or use nl2br/str_replace to manage paragraph breaks specifically.
echo $plainText;

This code outputs the exact text you requested: "The celebration of the Recon class in our second BF4 Class Week continues with a sneaky stroll down memory lane. Learn more about how the Recon has changed in appearance, name and weaponry over the years…".

One critical detail to note is the handling of non-breaking spaces (&nbsp;). In your example, there is a paragraph containing only &nbsp;. When you iterate through text nodes, this entity renders as a space. If you strictly want to remove empty paragraphs or entities that don't add semantic value, you may need to filter those out after extraction.

Another consideration is the handling of HTML entities like &hellip;. The DOM parser automatically decodes these into their character equivalents (the ellipsis). If you need them preserved as text entities for some reason, you would need to manually encode them back using htmlspecialchars, but typically for meta descriptions, decoded text is preferred.

For larger applications or when working with Laravel, consider checking if a helper package like symfony/html-sanitizer provides better utility, though the native DOM approach remains standard for pure PHP logic. If you are building a content management system where this extraction happens frequently, integrating this logic into a service layer keeps your controllers clean. Always ensure that the input HTML source is trusted or sanitized before loading it into a DOMDocument, as malicious scripts could theoretically execute if not handled carefully in certain contexts, although DOMDocument generally does not execute JavaScript.

Finally, remember that meta descriptions have strict character limits. Extracting all text from a blog post might result in a string far too long for a meta tag. You may need to truncate the resulting $plainText based on byte length or character count after extraction to ensure SEO compliance.

Our network