WP Custom Permalink Filter

strlen('') in substr_replace will always evaluate to 0, which doesn’t replace anything. It just inserts the new url at $pos.

You could use this:

function modify_attachment_link( $markup, $id ) {

    $pos = strpos( $markup, 'href' ) + 6;

    $remainstring = substr( $markup, $pos );
    $pos2 = strpos( $remainstring, "'" );

    $url = substr( $remainstring, 0, $pos2 );
    $url_length = strlen( $url );

    $url .= "#image-$id";
    return substr_replace( $markup, $url, $pos, $url_length );
}