Use of attachment_url_to_postid in WordPress

I did some image lookup via ajax from the Elementor Image Gallery, a place where I only had the image-url to get a meta data field attached to the image. To find the image id I instead used the WordPress helper function attachment_url_to_postid, that made the lookup for me.

But I found that sometimes the lookup didn’t work for some reason. After some digging I found that WordPress adds the ending ‘-scaled’ to the image, which makes the lookup function not finding the image since it’s not the original name.

// get the image url via ajax in some way, sanitize url as simple security check
$image_url = sanitize_text_field( $_REQUEST['image_url'] ); 

// get only the image file name, to avoid looking for cdn-url for example
$image_url = end(explode('/', $image_url));

// If the filename is an auto-generated thumbnail, remove the sizes and get the URL of the original image
$image_url_org = preg_replace( '/-\d+x\d+(?=\.(webp|jpg|jpeg|png|gif)$)/i', '', $image_url );

// do the same thing but add '-scaled' to the name if the first lookup fails
$image_url_scaled = preg_replace( '/-\d+x\d+(?=\.(webp|jpg|jpeg|png|gif)$)/i', '-scaled', $image_url );

// do the magic, find the actual image id, to be used to find meta data on for example
$image_id = attachment_url_to_postid($image_url_org);

// if the original name fails, try with the '-scaled' name added to it.
if ($image_id == 0) { // try to find image with scale ending if not found with original name
	$image_id = attachment_url_to_postid($image_url_scaled);

// hopefully now you got the id to return or do whatever you need with it.
return $image_id;