PHP Get Text from HTML Element

This is the another php tutorial, that’ll help to extract text between HTML tags. We’ll use the preg_match() function to extract text between HTML tags with REGEX in PHP.

The preg_match() function helps to get content between html tags using regular expressions with in PHP. You can also extract the content inside element based on class name or ID using PHP.

Get Text from HTML Element

Let’s get the content from the specific div (HTML element) using PHP.

$htmlContent = '<div class="desc">Hello! I am dev from phpflow...</div>';
preg_match('/<div class="desc">(.*?)<\/div>/s', $htmlContent, $match);
print_r($match);

Output:

Array ( [0] =>
Hello! I am dev from phpflow…
[1] => Hello! I am dev from phpflow… )

Using strip_tags Method

We can also extract text from html tag using strip_tags().

$htmlContent = '<div class="desc">Hello! I am dev from phpflow...</div>';
echo(strip_tags($htmlContent));

Output:

Hello! I am dev from phpflow…

Using html2text Package

The strip_tag() will not do much better job in complicated HTML code. You can use html2text package to extract text from html tags.

Install using composer:

composer require html2text/html2text

Example:

$html = new \Html2Text\Html2Text('Hello, "I am dev from phpflow"');
echo $html->getText();

Output:

Hello! I am dev from phpflow

References:

Leave a Reply

Your email address will not be published.