Home > Article > Backend Development > 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';
Breaking Down the Pattern
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];
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!