custom gallery filter with image caption as link title?

I found a working solution on the WordPress Forums.
Here’s the code:

function add_img_title_to_anchor($content) {

    /* Find internal links */

    //Check the page for linked images
    $search="/<a ([^>]*?)><img ([^>]*?)\/><\/a>/i";
    preg_match_all( $search, $content, $matches, PREG_SET_ORDER);

    //Check which attachment is referenced
    foreach ($matches as $val) {
        // Only if the Link doesn't already have a Title attribute, we work
        if (!preg_match("#title=#", $val[1])) {

            // Find all Link attributes and sanitize the Href att
            $anchor_temp = preg_match_all("#([a-z-]+?)=(['\"]{1})([^'\"]*)(['\"]{1})#", $val[1], $matches_anchor);
            foreach ($matches_anchor[1] as $key => $value) {
                $anchor_atts[$value] = $matches_anchor[3][$key];
            }

            // Find all Image attributes
            $img_temp = preg_match_all("#([a-z-]+?)=([\"]{1})([^\"]*)([\"]{1})#", $val[2], $matches_img);
            foreach ($matches_img[1] as $key => $value) {
                $img_atts[$value] = $matches_img[3][$key];
            }

            // Get the Image Title attribute and copy it to the Link attributes
            //  Case 1. If Image Title exists we use it
            if (isset($img_atts["title"]) && $img_atts["title"] != "") {
                $anchor_atts["title"] = $img_atts["title"];
            }
            //  Case 2. If no we use the Alt attribute
            else {
                $anchor_atts["title"] = $img_atts["alt"];
            }

            // Rebuilt the HTML tags
            $anchor_attributes = array();
            foreach ($anchor_atts as $key => $value) {
                $anchor_attributes[] = $key . '="' . $value . '"';
            }

            $img_attributes = array();
            foreach ($img_atts as $key => $value) {
                $img_attributes[] = $key . '="' . $value . '"';
            }

            // Replace the previous tags by the new
            $replacement="<a " . implode(" ", $anchor_attributes) . '><img ' . implode(" ", $img_attributes) . ' /></a>';

            $content = str_replace($val[0], $replacement, $content);
        }
    }

    return $content;

The original post is here: https://wordpress.org/support/topic/add-the-title-of-an-image-to-the-image-link-in-gallery