PHP: Get/Strip particular element from HTML

The below is the sample code for strip a particular HTML element from given string HTML. Using this function we can able to get particular div, span, p, body, article,.. any HTML wrapped element by its class or id. This function accepts 4 parameters, HTML string to get particular Tag, Strip tag name, Identifier name Class or Id and Identifier Class name or Id name.

Sample Code:  

/**
 * Custom function for get specific HTML tags.
 * @param $htmlString
 *  Original HTML string to extract specific HTML.
 * @param $tagName
 *  Tag that need to extract like div, span, p..
 * @param $identifierType
 *  Extract THML tag identifier type id or class.
 * @param $identifier
 *  Specific Class name or ID name to extract.
 * @return $result
 *  HTML string.
 */
function codeexpertz_get_specific_tags($htmlString, $tagName, $identifierType, $identifier) {
  $dom = new DOMDocument();
  $dom->loadHTML($htmlString);
  $xpath = new DOMXPath($dom);
  $div = $xpath->query('//' . $tagName . '[@' . $identifierType . '="' . $identifier . '"]');
  $div = $div->item(0);
  $result = $dom->saveXML($div);
  return $result;
}

Example:

 

$htmlString = '<div class="wrapper"><h2>CodeExpertz</h2><span class="welcome">Welcome to CodeExpertz</span></div>';
$tagName = 'span';
$identifierType = 'class';
$identifier = 'welcome';
print codeexpertz_get_specific_tags($htmlString, $tagName, $identifierType, $identifier);
<span class="welcome">Welcome to CodeExpertz</span>
Category: