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

How to Extract Content Between HTML Tags Using Regular Expressions in PHP?

Linda Hamilton
Release: 2024-11-09 21:42:02
Original
980 people have browsed it

How to Extract Content Between HTML Tags Using Regular Expressions in PHP?

Extracting Content Between HTML Tags in PHP

In PHP, extracting specific content from an HTML string can be achieved using regular expressions. To accomplish this, you need to define a regular expression pattern that matches the target tag and its content.

Understanding the Problem

You want to retrieve the content within the and tags from an HTML string, denoted as $content. You aim to extract, manipulate, and reinsert the matched string back into the original string.

Matching the HTML Code Tags

To achieve your goal, you can utilize the following regular expression:

$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
Copy after login

Breaking Down the Pattern

  • <: Matches the opening < character.
  • s*: Matches any number of whitespace characters.
  • code: Matches the literal string "code".
  • b: Ensures that typos (e.g., ) are not captured.</li> <li>[^>]*: Captures the content of the tag, including attributes.</li> <li>(.*?): Captures the content within the <code> and tags.
  • ]*>: Matches the closing tag and any attributes.
  • #s: Enables dot-all matching, allowing newlines to be captured.

Example Usage

You can implement this pattern in your code as follows:

$content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. <code>Donec sed erat vel diam ultricies commodo. Nunc venenatis tellus eu quam suscipit quis fermentum dolor vehicula.</code>";
preg_match($regex, $content, $matches);

// Extract the matched code block
$matchedCode = $matches[1];
Copy after login

By leveraging this regular expression, you can effectively extract the content between the and tags in your HTML string.

The above is the detailed content of How to Extract Content Between HTML Tags Using Regular Expressions in PHP?. 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