Home > Backend Development > PHP Tutorial > How to Parse HTML in PHP to Extract Text Between Headings Without Regular Expressions?

How to Parse HTML in PHP to Extract Text Between Headings Without Regular Expressions?

Susan Sarandon
Release: 2024-12-07 22:58:13
Original
986 people have browsed it

How to Parse HTML in PHP to Extract Text Between Headings Without Regular Expressions?

PHP Parse HTML Code

Q: How do I parse HTML code stored in a PHP variable to extract the text between headings, without using regular expressions?

A: Use PHP Document Object Model:

$DOM = new DOMDocument;
$DOM->loadHTML($html);
$items = $DOM->getElementsByTagName('h1');
for ($i = 0; $i < $items->length; $i++)
    echo $items->item($i)->nodeValue . "<br/>";
Copy after login

If you want the content between headings, use this regex:

echo preg_replace("#<h1.*?>.*?</h1>#", "", $html);
Copy after login

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template