Skip to content

Instantly share code, notes, and snippets.

@pulasthibandara
Last active November 15, 2016 21:14
Show Gist options
  • Select an option

  • Save pulasthibandara/8876f3fe00aaecd7dce41f962641b74c to your computer and use it in GitHub Desktop.

Select an option

Save pulasthibandara/8876f3fe00aaecd7dce41f962641b74c to your computer and use it in GitHub Desktop.
Regex for formatting NZ telephone numbers

regex for formatting NZ numbers

devides a given string of numbers. work with php, js, python

if an 0800 number:

(0800) 123 123 format

normal number:

023123123 -> (02) 322 3123

0123123123 -> (012) 312 3123

02123123123 -> (0212) 312 3123

/(0800|\d*?)(\d{3})(\d{4}|\d{3})$/
// js example
const regex = /(0800|\d*?)(\d{3})(\d{4}|\d{3})$/g;
const str = `0800123123`;
const subst = `(\$1) \$2 \$3`;
const result = str.replace(regex, subst);
// result = (0800) 123 123
<?php
// php example
$re = '/(0800|\d*?)(\d{3})(\d{4}|\d{3})$/';
$str = '0800123123';
$subst = '($1) $2 $3';
$result = preg_replace($re, $subst, $str);
// $result = (0800) 123 123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment