Home >Backend Development >PHP Tutorial >How to Extract Text Between Tags in PHP Without Using Regular Expressions?

How to Extract Text Between Tags in PHP Without Using Regular Expressions?

Linda Hamilton
Linda HamiltonOriginal
2024-12-18 13:05:25796browse

How to Extract Text Between  Tags in PHP Without Using Regular Expressions?

How to Parse HTML Code in PHP

Problem:
Extract the text between heading tags (

) from HTML code stored in a PHP variable.

Requirements:
Avoid using regular expressions.

Solution:

There are several techniques to parse HTML code in PHP. The recommended method for non-regular expressions is to use the PHP Document Object Model (DOM).

<?php
$str = '<h1T1</h1>Lorem ipsum.<h1T2</h1>The quick red fox...<h1T3</h1>... jumps over the lazy brown FROG!';
$DOM = new DOMDocument;
$DOM->loadHTML($str);

// Retrieve all heading elements
$items = $DOM->getElementsByTagName('h1');

// Extract and display the text content
for ($i = 0; $i < $items->length; $i++) {
    echo $items->item($i)->nodeValue . "<br\>";
}
?>

This code outputs:

T1
T2
T3

Extended Solution:
If you need to retrieve the content between heading tags, use the following regular expression:

<?php
$str = '<h1T1</h1>Lorem ipsum.<h1T2</h1>The quick red fox...<h1T3</h1>... jumps over the lazy brown FROG!';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

This code outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

The above is the detailed content of How to Extract Text Between Tags in PHP Without Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn