Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?
Note: I am rewriting an existing system that is painfully slow.
From stackoverflow
-
Use str_split():
$string = '0123456789012345'; $sets = str_split($string, 4); print_r($sets);The output:
Array ( [0] => 0123 [1] => 4567 [2] => 8901 [3] => 2345 )Then of course to insert hyphens between the sets you just implode() them together:
echo implode('-', $sets); // echoes '0123-4567-8901-2345'Rob : Assuming the OP wants the hyphens inserted, you'd probably then want to do implode( '-', $sets ).yjerem : Yeah, edited that in while you were commenting. At first I assumed he knew the implode() function.Unkwntech : I do, I know how to do this also, I was A) hoping for something different I didn't already know about, b) putting it out there for other persons, since I've been asked about this 3 times today.DreamWerx : What's the data source? If it's a DB, you can have the DB format it for you before it even gets to PHP. -
If you are looking for a more flexible approach (for e.g. phone numbers), try regular expressions:
preg_replace('/^(\d{4})(\d{4})(\d{4})(\d{4})$/', '\1-\2-\3-\4', '0123456789012345');If you can't see, the first argument accepts four groups of four digits each. The second argument formats them, and the third argument is your input.
Loki : I'm not sure if this wouldn't work better? preg_replace('/(\d{4})/', '-\1', '0123456789012345');strager : That wouldn't work, since you'd be left with a '-' hanging in the front of the output. It also kills some of the flexibility. I have edited my post to use the {4} syntax, though. -
This is a bit more general:
<?php // arr[string] = strChunk(string, length [, length [...]] ); function strChunk() { $n = func_num_args(); $str = func_get_arg(0); $ret = array(); if ($n >= 2) { for($i=1, $offs=0; $i<$n; ++$i) { $chars = abs( func_get_arg($i) ); $ret[] = substr($str, $offs, $chars); $offs += $chars; } } return $ret; } echo join('-', strChunk('0123456789012345', 4, 4, 4, 4) ); ?>
0 comments:
Post a Comment