Php

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:

Related Post
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:

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories