Extract HTML tags and its content from a string Goal

I want to extract HTML tags and its content from a string. The content (input) is queried from WordPress database.

Sample data (input)

I extract this dummy data from my WordPress database: https://www.phpliveregex.com/p/tan
I believe this should cover all the needed tags to parse.

Expectation (output)

Accepting a HTML-format string as input.
The output should be able to return a string which could be any of these:


The HTML element string itself
Attributes string of the HTML element
Text nodes, child nodes string of the HTML element


My concern


Which solutions take less execution time?
Which solutions save more server memory?
Security vulnerable of each solutions.


Solutions

I've come up with a 2 solutions by myself. It works fine, but I don't know which one is good for my case.

Regex pattern

$el = 'li'; // Ex
$match = []; // Reserving for results

/**
 * Regex - extract HTML tag and its content
 * Array map:
 * x[0] = everything
 * x[1] = open tag
 * x[2] = attributes
 * x[3] = content &amp; end tag
 * x[4] = content only
 * 
 * Note for content: including text node + children node
 */
$reg = '/(&lt;'.$el.'(.*?)&gt;)((\n*?.*?\n*?)&lt;\/'.$el.'&gt;|)/';

if (preg_match($reg, $html_str, $match)) { echo 'Moving onward!';}


Result: see demo of regex

DOM object

$dom = new DomDocument();
$content = mb_convert_encoding(
    get_the_content(null, true), # WordPress func, it gives input str
    'HTML-ENTITIES',
    'UTF-8'
);
$dom-&gt;loadHTML($content);

$el = $doc-&gt;getElementsByTagName('li');


Result: returning a DOMNodeList and I have to do few more tasks to print it to a string which can be used.
Using regex to parse valid html will work (and you might call it beautiful) until it doesn't work... then you'll bend over backwards (over and over) each time you encounter an anomaly then try to write a patch for the pattern.

Allow me to notify you of a simple, valid html occurrence that will break your sample pattern:

Demo

&lt;link rel="stylesheet" href="/html_5/tags/html_link_tag_example.css"&gt;


It would match because your li needle is not immediately followed by a word boundary character (\b). Is this a simple thing to fix? Yes, but my point remains -- regex is an inappropriate tool for parsing valid html.

I generally rely on DomDocument for most cases and when XPath makes life simpler, I use that to perform clean, readable queries on the document.

This is one time when focussing on speed is a moot point -- speed is the least of your worries.  What good is speed if the results are bogus? The goal should be to design a robust and reliable script using DOM-aware techniques.