php-regexHow to match an HTML tag using regex in PHP?
Matching HTML tags using regex in PHP can be done using the preg_match() function. This function takes two parameters, the first being the regular expression pattern and the second being the string to match against.
$html = '<p>This is a paragraph</p>';
if (preg_match('/<p>(.*?)<\/p>/', $html, $matches)) {
echo $matches[1];
}
The output of the above code will be:
This is a paragraph
Code explanation
preg_match(): This is the PHP function used to match a regular expression pattern against a string./<p>(.*?)<\/p>/: This is the regular expression pattern used to match an HTML paragraph tag. The<p>and</p>are the opening and closing tags, and the.*?is a wildcard that matches any character.$matches: This is an array that will contain the matches found by the regular expression.echo $matches[1]: This will output the contents of the first match found by the regular expression.
Helpful links
More of Php Regex
- How to use PHP regex to match a zip code?
- How to match a quotation mark in PHP regex?
- How to use PHP regex to match a year?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match an exact string?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match special characters?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
See more codes...