Last active
August 6, 2019 06:57
-
-
Save cthurston/566978be72a62c28041f086d2f10373d to your computer and use it in GitHub Desktop.
A postgres function that attempts to format phone number to RFC 3966
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION "public"."format_phone_number"(text) | |
RETURNS "pg_catalog"."text" AS $BODY$ | |
BEGIN | |
RETURN | |
regexp_replace( | |
regexp_replace( | |
regexp_replace( | |
regexp_replace( | |
regexp_replace( | |
regexp_replace( | |
regexp_replace( | |
regexp_replace( | |
$1, | |
'((?!^\+)\+)|(x(?=.*?x))|([^\+0-9x])', | |
'', | |
'g' | |
), | |
'x$', | |
'', | |
'g' | |
), | |
'x', | |
';ext=', | |
'g' | |
), | |
'(\d{4}?($|;ext=))', | |
'-\1', | |
'' | |
), | |
'(\d{3}-\d{4}?($|;ext=))', | |
'-\1', | |
'' | |
), | |
'(\d{3}-\d{3}-\d{4}?(?:$|;ext=))', | |
'-\1', | |
'' | |
), | |
'^(\d(.+)?-\d{3}-\d{3}-\d{4}?(?:$|;ext=))', | |
'+\1', | |
'' | |
), | |
'^(\+-|-)', | |
'', | |
'g' | |
); | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE | |
COST 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment