Kylie
Kylie

Reputation: 11749

Weird whitespace error in PHP

I have phone numbers that I want to format

And I have a pattern matcher that breaks down the numbers into a 10 digit format, and then applies dashes. It works most of the time. However Im having an issue with certain numbers.

$trimmed = trim(preg_replace('/\s+/', '', $v->cust_num));
$tendigit = str_replace(array( '(', ')','-',' ' ), '', $trimmed);
$num = substr($tendigit,0,3)."-".substr($tendigit,3,3)."-".substr($tendigit,6,4);

This will change (555)555 5555, or 555-555 5555 or 5555555555 or (555)-555-5555 or 555-555-5555 to my format of 555-555-5555

However, I came across a few entries in my database, that dont seem to want to change.

One of the bad entries is this one. It contains two white spaces infront of the 4.

   4-035-0100

When it runs through $trimmed, and I output $tendigit...it outputs

  40350100 

as expected. But then when I apply $num to it. It goes back to

 4-035-0100

I would at least expect it to be

 403-501-00

It seems there is some hidden whitespace in it, that my preg_replace, trim, and str_replace are not attacking.

Any ideas??

Thanks

Upvotes: 0

Views: 99

Answers (2)

Jonathan
Jonathan

Reputation: 1564

You can condense your code a little:

$tendigit = preg_replace('/[^\d]/', '', $v->cust_num);
$num = substr($tendigit,0,3)."-".substr($tendigit,3,3)."-".substr($tendigit,6,4);

Though, you should add in some conditions to check that the phone number actually has 10 digits too:

$tendigit = preg_replace('/[^\d]/', '', $v->cust_num);
if(strlen($tendigit == 10)){
    $num = substr($tendigit,0,3)."-".substr($tendigit,3,3)."-".substr($tendigit,6,4);
} else {
    // catch your error here, eg 'please enter 10 digits'
}

The first line removes any 'non-digit' [^\d].

The conditional statement checks if the $tendigit variable has 10 digits in it.

If it does, then it uses your code to parse and format.

If it doesnt, then you can catch an error.

Upvotes: 0

codeaken
codeaken

Reputation: 884

The code below works, I have tried it with the special characters we discovered in the comments. Basically, the regex removes everything that isnt a number (0-9) and then uses your original formatting.

$trimmed = preg_replace('/\D+/', '', $v->cust_num);
$num = substr($trimmed,0,3)."-".substr($trimmed,3,3)."-".substr($trimmed,6,4);

Upvotes: 0

Related Questions