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 special characters?
- How to use PHP regex with the "x" modifier?
- How to match a double quote in PHP regex?
- How to use PHP regex to match UUID?
- How to use PHP regex to match whitespace?
- How to match a plus sign in PHP regex?
- How to match a single quote in PHP regex?
- How to use quantifiers in PHP regex?
- How to use the "s" modifier in PHP regex?
- How to use PHP regex to match a boolean value?
See more codes...