You are here: Home / Topics / How to Extract Content Between HTML Tags in PHP

How to Extract Content Between HTML Tags in PHP

Filed under: PHP on 2023-06-30 06:19:58

In this tutorial, we are going to see how to extract content between HTML tags in PHP. preg_match() function is the easiest way to extract text between HTML tags with REGEX in PHP. If you want to get content between tags, use regular expressions with the preg_match() function in PHP. You can also extract the content inside the element based on the class name or ID.

The code snippet below shows how to get the content inside the div block. The following code uses preg_match() with a regular expression to extract text or HTML.
 

How to Extract Content Between HTML Tags in PHP


<?php
 $html = '<div class="test">Lorem ipsum dolor sit amet.</div>';
 preg_match('/<div class="test">(.*?)<\/div>/s', $html, $match);
?>


The result will be stored in $match variable. if you are running the code in the browser, you should inspect the element to see the difference between $match[0] and $match[1].

Extract the content, including the parent element (tags):

echo $match[0];

Output:

<div class="test">Lorem ipsum dolor sit amet.</div>


Extract the content between tags:


echo $match[1];


Output:

Lorem ipsum dolor sit amet.

About Author:
V
Vinay Kumar     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.