Jump to content

Clean Mobile Number


jaymc

Recommended Posts

This may be a stupid question but whats the best way to clean a mobile number from invalid chars without messing up the mobile itself

 

Mobile numbers I am having to deal with are for example like this

 

[44] 07783784123

[44] 07783-784-123

[44] 07 783 784 123

[07783784123]

447783784123

 

The end result must be 07783784123

 

Some mobiles can have 10/11 chars in, so it may be difficult to strip out all the bad characters and then just split leaving the last 11 chars..

Link to comment
https://forums.phpfreaks.com/topic/159684-clean-mobile-number/
Share on other sites

It may be a quicker process if you just build an array and use str_replace;

 

<?php
function sleanMobileNumber($number) {
$replace = array('[44]', '[', ']', ' ', '-');
$mob_num = str_replace($replace, "", $number);
if(substr($mob_num, 0, 2) == '44') {
	$mob_num = substr_replace($mob_num, '', 0, 2)
}
}

Link to comment
https://forums.phpfreaks.com/topic/159684-clean-mobile-number/#findComment-842234
Share on other sites

If I understand correctly, would something like this be along the lines of what you are looking for?

 

Example:

$phoneNumber = array('[44] 07783784123', '[44] 07783-784-123', '[44] 07 783 784 123', '[07783784123]', '447783784123');
foreach($phoneNumber as $val){
$val = preg_replace('#[^0-9]#', '', $val);
$valLen = strlen($val);
$val = ($valLen == 10 || $valLen == 12 ? substr($val, -10) : ($valLen == 13 || $valLen == 11 ? substr($val, -11) : 'Illegal Format!'));
echo $val . "<br />\n";
}

 

Output:

07783784123
07783784123
07783784123
07783784123
7783784123

 

That ternary operator could also be replaced with the more traditionally readable if() {...}else{...} statement instead:

if($valLen == 10 || $valLen == 12){
	$val = substr($val, -10);
} else if($valLen == 13 || $valLen == 11){
	$val = substr($val, -11);
} else {
	$val = 'Incorrect Format!';
}

 

Just a note:

The end result must be 07783784123

 

I question how this would be with the last example being 447783784123 (unless I'm missing something here).

 

Link to comment
https://forums.phpfreaks.com/topic/159684-clean-mobile-number/#findComment-842449
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.