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. The regular expression pattern to match an HTML tag would be: '/<[^>]+>(.*)</[^>]+>/'
Here is an example of how you can use preg_match() to extract the string value of a specific HTML tag:
<?php
$html = '<p>This is a paragraph.</p>';
preg_match('/<p[^>]*>(.*)<\/p>/', $html, $matches);
echo $matches[1]; // Outputs: "This is a paragraph."
This will match the <p>
tag and it's content and store it in the matches array. The actual match is stored in the first element of the array i.e. $matches[1]
You can also use regular expression 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:
<?php
$html = '<p>This is a paragraph.</p>';
preg_match_all('/<p[^>]*>(.*)<\/p>/', $html, $matches);
print_r($matches[1]);
This will store all the matches in the $matches array, with each match being an element of the array.