How can one effectively extract HTML comments from a string using PHP?

To extract HTML comments from a string using PHP, you can use regular expressions to search for comment tags <!-- and --> and extract the content in between. You can achieve this by using the preg_match_all function in PHP with the appropriate regular expression pattern.

&lt;?php
$string = &quot;&lt;!-- This is a comment --&gt; This is some text &lt;!-- Another comment --&gt;&quot;;
$pattern = &#039;/&lt;!--(.*?)--&gt;/&#039;;
preg_match_all($pattern, $string, $matches);
$comments = $matches[0];

foreach ($comments as $comment) {
    echo $comment . &quot;\n&quot;;
}
?&gt;