2

I'm new at stackoverflow, hope find my solution here :)

Using PHP, i want a php function like:

function getHtmlTags($html_source, $tag='div', $by_attr="class", $attr_value="class_name"){
}

Ex: if 1 found, Should returns an array like so :

array([0] => '<div class="class_name">blah blah</div>');

I searched everywhere :( haven't found the solution! please help

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
Barry
  • 43
  • 1
  • 5

1 Answers1

1

Load your HTML document into a Document Object Model and use XPath to find the element(s) based on the parameters given.

Regarding your regex tag - read this before descending into that nightmare - RegEx match open tags except XHTML self-contained tags

For example (warning - completely untested)

/**
 * @return DOMNodeList
 */
function getHtmlTags($html_source, $tag='div', $by_attr="class", $attr_value="class_name")
{
    $document = new DOMDocument();
    if (!$document->loadHTML($html_source)) {
        throw new Exception('Invalid HTML source');
    }

    $xpath = new DOMXPath($doc);

    $query = sprintf('//%s[%s="%s"]', $tag, $by_attr, $attr_value);

    return $xpath->query($query);
}
Community
  • 1
  • 1
Phil
  • 157,677
  • 23
  • 242
  • 245