Skip to content

Instantly share code, notes, and snippets.

@lukearmstrong
Last active May 2, 2024 12:08

Revisions

  1. lukearmstrong revised this gist Jun 28, 2013. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions format-phone.php
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    <?php

    /*
    $original = '+44 (0)1234 567 890';
    $original = '0044 01234 567 890';
  2. lukearmstrong renamed this gist Jun 28, 2013. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. lukearmstrong created this gist Jun 28, 2013.
    32 changes: 32 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    /*
    $original = '+44 (0)1234 567 890';
    $original = '0044 01234 567 890';
    $original = '01234 567 890';
    $original = '44 1234 567 890';

    Result should always be:
    '+441234567890
    */

    // Strip out all characters apart from numbers
    $phone = preg_replace('/[^0-9]+/', '', $original);

    // Remove the 2 digit international code (+44)
    if (substr($phone, 0, 2) == '44') {
    $phone = substr($phone, 2);
    }

    // Remove the 4 digit international code (0044)
    if (substr($phone, 0, 4) == '0044') {
    $phone = substr($phone, 4);
    }

    // Remove the initial Zero from the number
    // Some people write it in international numbers like this: +44 (0)1234 567 890
    // But it shouldn't be entered when dialling
    if (substr($phone, 0, 1) == '0') {
    $phone = substr($phone, 1);
    }

    // Add the international prefix
    $phone = '+44' . $phone;