replace: $url = str_replace('details.php', 'img'.$matches1[1].'.'.$matches2[1].'.htm', $url);
with: $url = str_replace('details.php', 'img'.$matches1[1].(($matches2[1] != "search") ? '.'.$matches2[1] : "").'.htm', $url);
but I must warn u, u will loose feature that displays previous/next image from the search result in the image details page.