Converting restricted html in comments to bbcode

I eventually solved this with a slightly different approach. This allows users to include images in their comments. One issue I’m still having, which is really a whole new question, but worth mentioning here, is that the user may not be allowed to upload new images to the post, and only include images already in the library.

function html2bbcode( $commentdata ) {
  if(!is_admin()) {
    $xhtml = $commentdata['comment_content'];

    $parsed_comment="";

    $dom = new DOMDocument();
    $dom->loadHTML($xhtml);
    $img_tags = $dom->getElementsByTagName('img');

    foreach ($img_tags as $img) {
            $src = (string) $img->getAttribute('src');
            if($src == '') {
                // No image src, no worries. 
            } else {
                $src = str_replace('"', "", $src);
                $alt = (string) $img->getAttribute('alt');
                $img_class = (string) $img->getAttribute('class');

                $bbcode=" [img=".$alt.']'.$src.'[/img] ';

                    $divNode = $dom->createElement('div');
                    $textNode = $dom->createTextNode($bbcode);
                    $divNode->appendChild($textNode);

                    $img->parentNode->replaceChild($divNode, $img);            
            }
    }
    $parsed_comment = $dom->saveHTML();
    $parsed_comment = str_replace('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">','',$parsed_comment);

    $commentdata['comment_content'] = $parsed_comment;

  }
  return $commentdata;
}
add_filter( 'preprocess_comment' , 'html2bbcode' );