Search code examples
phpstr-replacetrim

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


Solution

  • 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);