What are the limitations of using regular expressions to remove comments from PHP code?

Regular expressions may struggle to accurately remove comments from PHP code because they cannot handle nested comments or comments within strings. To accurately remove comments, it is recommended to use a parser that understands the syntax of the language, such as a PHP parser. This will ensure that all comments are properly removed without affecting the functionality of the code.

// Example PHP code snippet using a PHP parser to remove comments
$code = file_get_contents('example.php');

$tokens = token_get_all($code);
$newCode = '';

foreach ($tokens as $token) {
    if (is_string($token)) {
        $newCode .= $token;
    } else {
        list($id, $text) = $token;
        if ($id != T_COMMENT && $id != T_DOC_COMMENT) {
            $newCode .= $text;
        }
    }
}

echo $newCode;