US Phone Numbers - Set the Area Code and Prefix Only to Variables
I have a question regarding finding characters (numbers in my case) in the middle or at the beginning of a string only.
I'm working with 10 digit US phone numbers and I would like to save the area code and the prefix of the phone number in to two separate variables. For now I'm just echoing them out because I can't get it to work right but later I'll search a database using the variables to determine the telephone service provider.
I need to be able to cut and paste a list of phone numbers without typing them all in. I'm using a text area for this and this is what I have right now:
<?php
if (isset($_POST['submit'])) {
$fullnumber = trim($_POST['numbers']);
$onenumber = explode("\n", $fullnumber);
foreach ($onenumber as $line) {
$area = substr("$line", 0, -7); // returns the first three numbers of the phone number
$prefix = substr("$line", 3, -4); // returns the 3rd, 4th and 5th digit of the phone number
echo "Area code: " .$area;
echo "<br />";
echo "Prefix: " .$prefix;
echo "<br />";
}
}
else
{
?>
<html>
<head>
<title>Phone Verification</tit开发者_如何学编程le>
</head>
<body>
<br />
<form method="post" action="<?php echo $PHP_SELF;?>">
Enter Phone Numbers:<br />
<textarea rows="20" cols="10" name="numbers" wrap="physical"></textarea>
<input type="submit" value="submit" name="submit">
</form>
<?php
}
?>
What's happening is the phone numbers will have 4 digit area codes and 4 digit prefixes except for the last one which will be displayed correctly with 3 digit for the area code and prefix.
What am I doing wrong?
Try explode
ing on \r\n
rather than just \n
- I'm guessing your data includes carriage returns as well as line feeds which is skewing your substrings.
string substr ( string $string , int $start [, int $length ] ) parameters are start, length (stop). Assuming you have a number with no spaces or additional characters as such 5553332222 change this
$area = substr("$line", 0, -7);
$prefix = substr("$line", 3, -4);
to this
$area = substr("$line", 0, 3); // start at 0, go 3 (555)
$prefix = substr("$line", 3, 3); // start at 3 go 3 (333)
精彩评论