简体   繁体   中英

Split data without delimiter?

Ok say I have my phone numbers stored in my table as:

"0008675309"

I obviously wouldn't want to display it just like that, I'd want to format it when I call it as:

(000)867-5309

Would it be better to store it in the database with a delimiter such as / - or. So that I can split it later? Or is it possible to split it by the number of characters?

The performance cost and code to process a phone number in any of those formats is simple, so it's really up to your preference. To answer your question, it is very easy to grab the first three characters, the next three, and the last four using for example, substr function.

If you are only storing North American phone numbers (10 digits), then as @mellamokb noted, you're ok either way. If you may be storing international numbers, you should capture as much detail as you can early on (if possible) since it might be hard to know how to punctuate the number later on.

use preg_split with PREG_SPLIT_NO_EMPTY

Here is a one liner that does what you want:

$phone = preg_replace('^(\d{3})(\d{3})(\d{4})$', '($1)$2-$3', $phone);

As a added bonus it won't change the format if the input format doesn't match (international numbers).

The other answers are perfectly correct. In case you wanted the actual code for it, I think the following should do the trick (the indexes may be off by one oops:):

$phone_number="0008675309"
$phone_number=substr_replace($phone_number, "(", 0, 0);
$phone_number=substr_replace($phone_number, ")", 4, 0);
$phone_number=substr_replace($phone_number, "-", 8, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM