This may not be the most efficient way to do it but it works.
code:
<?php
$str = "index.php?spgmGal=rav&spgmPic=7&title=something#spgmPicture";
echo transformlink($str);
function transformlink($str) {
#get title
preg_match('/title=[A-Za-z0-9 ]+/', $str, $matches, PREG_OFFSET_CAPTURE);
$title = substr($matches[0][0], 6);
    
    #check if spgmGal is there
    if (preg_match("/spgmGal=[A-Za-z0-9 ]+/", $str)) {
        preg_match('/spgmGal=[A-Za-z0-9 ]+/', $str, $matches, PREG_OFFSET_CAPTURE);
        $spgmGal = substr($matches[0][0], 8);
    } else {
        $spgmGal = null;
    }
    #check if spgmPic is there
    if(!is_null($spgmGal)) {
        preg_match('/spgmPic=[A-Za-z0-9 ]+/', $str, $matches, PREG_OFFSET_CAPTURE);
        $spgmPic = substr($matches[0][0], 8);
    } else {
        $spgmPic = null;
    }
#get spgmPicture anchor
preg_match('/#[A-Za-z0-9 ]+/', $str, $matches, PREG_OFFSET_CAPTURE);
$spgmPicture = $matches[0][0];
#return transformed link
$thelink = (!is_null($spgmGal)) ? '/'.$title.'/'.$spgmGal.'/'.$spgmPic.$spgmPicture : '/'.$title.$spgmPicture;
return $thelink;
}
?>