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

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

DDD
DDDOriginal
2024-11-10 16:28:02887browse

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

Extracting Content Between HTML Tags in PHP

When working with HTML, there are situations where you need to isolate specific content enclosed within HTML tags. To achieve this in PHP, you can leverage the power of regular expressions.

Grabbing HTML Tag Content

Suppose you have an HTML string containing various text and specific content marked by a pair of HTML tags, like and . Your goal is to extract the content within these tags.

To do this, you can use the following regular expression:

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

Breaking Down the Regular Expression

  • b asserts that the word boundary ensures that typos or variations are not captured.
  • [^>]* matches any content within the opening and closing code tags.
  • (.*?) captures the content between the tags in a non-greedy manner.
  • s flag allows the regex to capture multiline content.

Example Usage

Consider the following HTML string:

$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>"

By applying the regular expression to this string, you can successfully extract the content within the tags:

$code = preg_match($regex, $content, $matches);

The extracted content will be stored in the $matches array. You can then perform necessary operations on the extracted string and reinsert it into the original HTML content.

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