Home >Backend Development >PHP Tutorial >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
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!