How to Extract Content Between HTML Tags in PHP

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
	$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];


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

Extract the content between tags:

echo $match[1];


Lorem ipsum dolor sit amet.

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *