public function remove_rfc2822_comments($string)
{
$string = (string) $string;
$position = 0;
$length = strlen($string);
$depth = 0;
$output = '';
while ($position < $length && ($pos = strpos($string, '(', $position)) !== false) {
$output .= substr($string, $position, $pos - $position);
$position = $pos + 1;
if ($pos === 0 || $string[$pos - 1] !== '\\') {
$depth++;
while ($depth && $position < $length) {
$position += strcspn($string, '()', $position);
if ($string[$position - 1] === '\\') {
$position++;
continue;
} elseif (isset($string[$position])) {
switch ($string[$position]) {
case '(':
$depth++;
break;
case ')':
$depth--;
break;
}
$position++;
} else {
break;
}
}
} else {
$output .= '(';
}
}
$output .= substr($string, $position);
return $output;
}