I have the following PHP code that is suppose to remove the 'excess' text when a user enters it in a field. I have the following code as follows:
$mobileNumber = '00 356 99048123';
$excessMobileNumbers = array(//remove excess items in mobile number such as dialing codes and empty spaces
// ' ' => '',
'00356' => '',
'+356' => '',
'356' => '',
'00' => '',
);
The output is 99048123
The above code works well as it the number 99048123 doesn't contain 356 or 00.
But when I use this number 00 356 99008123, the number 99008123 contains 00. I want it only to remove the 00 in the 00 i.e. starting from the left hand side and leaving without removing the 00 in the 99008123.
How do I go about it? I use the array as a 'filtering' system.
Thanks
Clarification It is not only for 00 even for 356, if the number is 99048123 it works fine. If this number 99035612 since it has 356 withing it it does not work.
SOLUTION I discovered this solution which seems to work for my problem.
$mobileNumber = '00 356 99048000';
$mobileNumber = str_replace(' ','',$mobileNumber); // UPDATE
$excessMobileNumbers = substr($mobileNumber, 0, -8);
$mobileNumber = str_replace($excessMobileNumbers,'',$mobileNumber);
echo $mobileNumber;
Thank you all for your contribution.
As @ende-neu suggests simply explode out the string on a space and just take the last element in the array.
For the example you give this would look like:
$mobileNumber = '00 356 99048123';
$mobile_array = explode(' ',$mobile_number);
$my_number = end($mobile_array); //will give you 99048123
echo $my_number;
Although to be honest you're probably better off with a regular expression type approach or use a solid library such as libphonenumber for PHP
As some suggested, try this:
$mobileNumber = '00 356 99048123';
$mobileNumberParts = explode(" ", $mobileNumber);
echo end($mobileNumberParts);
output: 99048123
Use preg_replace
to remove all of your listed "prefixes" (only when at the beginning (^))
$number = preg_replace('/^(00|00365|\+365|365)/', '', $mobileNumber);
That is much safer than just splitting at white space because some people might add more white space in between the last part to improve readability.
You could use regex to strip out all non-numeric characters:
preg_replace("/[^0-9]/", "", $mobileNumber);
and then use substr
to grab the part that you want:
$my_number = substr($mobileNumber, -8);
This way if a number is passed in like:
$mobileNumber = '00 356 99-048-123';
or any other non-numeric characters are inside the part you actually want, after stripping out those characters you always know the last 8 characters are the numeric digits you are after.
I discovered this solution and it seems to work for my case
$mobileNumber = '00 356 99048000';
$mobileNumber = preg_replace("/[^0-9]/", '', $mobileNumber);
$excessMobileCharactors = substr($mobileNumber, 0, -8);
$mobileNumber = str_replace($excessMobileCharactors,'',$mobileNumber);
echo $mobileNumber;
Thank you all for your kind help.