Forum Moderators: coopster
Split your variables by finding the positions of these characters with strpos, and then selecting the part of the string you want on that basis with substr. trim might come in handy too.
The string functions: [be2.php.net...]
preg_split()would be handy here. Here it is in a function:
function phone_number($phone_number)
{
$pattern = "/[^\d]+/";
$phone_number = array_values [php.net](array_filter [php.net](preg_split [php.net]($pattern, $phone_number)));
if (count [php.net]($phone_number) < 3) array_unshift [php.net]($phone_number, '');
return $phone_number;
}
$phone_numbers = array(Having a look at the function, we find a pattern that says, "find anything that is not a number between 0 and 9".
'(123) 456-7890',
'123 456-7890',
'123 456 7890',
'(123) 456-7890',
' (123) 456-7890',
' (123)456-7890',
' (123) 456 - 7890',
'456 - 7890',
'() 456 - 7890',
'( ) 456 - 7890',
'456 7890',
'456-7890'
);
foreach ($phone_numbers as $phone_number) {
list [php.net]($area_code, $exchange, $number) = phone_number($phone_number);
print "area code: $area_code\nexchange: $exchange\nnumber: $number\n\n";
}
Use
preg_split()to split the string ($phone_number) on the pattern and put the captured values into an array; this array may have a blank in it in the very first array element. Why? Because the very first split value is going to be anything in front of the first non-numeric value found (such as the first parentheses of the area code, or an empty set of parentheses). In this case, it's nothing, and will always have to be nothing. Therefore, keep in mind that this function will work only if a somewhat properly formed phone number is passed to it. All the values in the array given work just fine. Use a regular expression to make sure you have a properly formatted phone number.
Next, use an
array_filter()without a callback to get rid of the
NULLvalue found in front of the area code, then the
array_valuessimply restructures the numerical indexes of the array. This is important because
listassumes that the numerical indices start at 0. Use
countto figure out if there is an area code in the phone number or not. If not, throw an empty area code onto the front of the array using PHP's
array_unshift()function (all numerical array keys will be modified to start counting from zero).