PHP/regex: How to get the string value of HTML tag?
In PHP, you can use the preg_match() function to extract the string value of an HTML tag.
In PHP, you can use the preg_match() function with the regular expression pattern '/<[^>]+>(.*)<\/[^>]+>/' to extract the string value of an HTML tag.
Here is an example of how you can use preg_match() to extract the string value of a specific HTML tag:
Example of using the preg_match() function to extract the string value of an HTML tag in PHP
<?php
$html = '<p>This is a paragraph.</p>';
preg_match('/<p[^>]*>(.*)<\/p>/s', $html, $matches);
echo $matches[1]; // Outputs: "This is a paragraph."This will match the <p> tag and its content and store it in the $matches array — the full match in $matches[0] and the captured group in $matches[1].
You can also use regular expressions to extract the string value of multiple HTML tags. For example, you can use the following regular expression to extract the string values of multiple <p> tags in an HTML document:
Example of using regular expression to extract the string value of multiple HTML tags in PHP
<?php
$html = '<p>First paragraph.</p><p>Second paragraph.</p>';
preg_match_all('/<p[^>]*>(.*)<\/p>/s', $html, $matches);
print_r($matches[1]);This will store all the matches in the $matches array, with each captured group available as an element in $matches[1].
Note: Regular expressions are fragile for parsing HTML. For production use, consider using
DOMDocumentor a dedicated HTML parser.