I would love a fresh pair of eyes looking at my problem which is driving me mad. Any help would be appreciated.
From just 2 lines of PHP code im trying to strip the first '44' if a user enters it at the start of there phone number:
$telephone = '44789562356';
$telephone = str_replace(' ','',$telephone);
$telephone = str_replace('+44','0',$telephone);
if(strpos($telephone,"44")==0){
$telephone = substr($telephone,2);
$telephone = '0'.$telephone;
}
Why is it that it strips '7's from all the phone numbers?
Like Colin commented, you need to use a strict comparison ===
on the return from strpos()
since it returns false
if the substring is not found, and 0
if it's at the beginning of the string and false == 0
is true, and false === 0
is false.
Alternatively, you can use regular expressions to specify matching only at the beginning of the string like so:
if( preg_match('/^44/', $telephone) ) { ... }
Or do the replacment with it:
preg_replace('/^44/', '0', $telephone);
Your code can be simplified to the following:
$telephone = '+44-789 56-2356 ask for larry';
$telephone = preg_replace('/[^0-9]/','',$telephone); // remove all non-numeric characters
$telephone = preg_replace('/^44/','0',$telephone);
echo $telephone;
// output: 0789562356