Skip to content

Instantly share code, notes, and snippets.

@cthurston
Last active August 6, 2019 06:57
Show Gist options
  • Save cthurston/566978be72a62c28041f086d2f10373d to your computer and use it in GitHub Desktop.
Save cthurston/566978be72a62c28041f086d2f10373d to your computer and use it in GitHub Desktop.
A postgres function that attempts to format phone number to RFC 3966
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