How to extract text between 2 tags by using PHP

In this tutorial I will explain how you can extract text between 2 tags by using PHP language. By using this way you can easily extract text from,<title></title>,<div></div>,<p></p>, etc.

So, create a new function in PHP like this:

function gettext($string, $tag)
{
$content ="/<$tag>(.*?)<\/$tag>/";
preg_match($content, $string, $text);
return $text[1];
}

Then, to extract text, use this code:

$newstring = "<div>dvsdvuihuidv</div><h4>dvvvvvvxs</h4>";

echo gettext($newstring,"h4");

results: dvvvvvvxs









Leave a Comment