January 29th, 2014, 10:37 PM
Solid regext and substr
I need to make sure I end up with a number with this format:
1 - Start with 61
2 - Followed by 9 digits.
For example all numbers below should end up like this:61405333535
0405 333 535
So far I have this and seems to work fine. Any tips or issues I missed?
$phone = $_GET['phone'];
//remove everything but numbers
$phone = preg_replace("/[^0-9]/","",$phone);
//Remove 0 from begining if exists
if (substr($phone, 0, 1) === '0')
$phone = ltrim ($phone,'0');
//If already has 61, remove it
if(substr($phone,0,2) == '61')
$phone = ltrim ($phone,'61');
$phone = "61".$phone;
January 30th, 2014, 01:24 AM
this is actually wrong. In any case, it's very cumbersome and user-hostile.
The function call ltrim($phone, '61') removes every "6" and "1" from the beginning of the number. So if my phone number happens to be +61666111666, I end up with an empty string. The second argument of ltrim() is treated as a list of characters, not a single prefix. And the function removes as many characters as possible. See the manual.
Silently modifying user data is generally a very bad idea. I do not want you to somehow guess my phone number. If I make a mistake, I want to be told so that I can correct it.
Start by defining the acceptable input. It would be something like this (after you've removed the whitespace):
You can make it more permissive, but all obvious mistakes should be rejected.
The end-user number is stored in the first capturing group. So you can take it and simply prepend "61" (shouldn't that be "+61"?). This automatically gives you the desired format.
Last edited by Jacques1; January 30th, 2014 at 01:34 AM.
January 30th, 2014, 03:41 AM
That is how they have desgined it. I thought +61 would make more sense but they want to see the number start with 61.
Originally Posted by Jacques1