Any php string function to do something like this?
Question
$length = strlen($s);
if($length == 10)
{
$newval = '';
for($i = 0; $i < 10; $i++)
{
$newval .= $s[$i];
if($i == 2 || $i == 5)
{
$newval .= '-';
}
}
}
If anybody knows what kind of a string function I would use, please let me know.
Solution
A simple string operation should be kept simple, so go with the most straight forward solution:
$str = substr($input, 0, 3).'-'.substr($input, 3, 3).'-'.substr($input, 6);
But as usually, there are several ways to skin a cat, so you have options. Like:
$str = sprintf('%s-%s-%s', substr($input, 0, 3), substr($input, 3, 3), substr($input, 6));
Or alternatively
$str = preg_replace('/^(.{3})(.{3})(.*)$/', '\1-\2-\3', $input);
Or alternatively
$str = preg_split('//', $input);
if (5 > count($chrs)) {
array_splice($chrs, 4, 0, '-');
}
if (3 > count($chrs)) {
array_splice($chrs, 2, 0, '-');
}
$str = implode('', $chrs);
OTHER TIPS
Sure, you can use substr
to accomplish this:
if(strlen($s) == 10) {
$s = substr($s, 0, 3) . '-' . substr($s, 3, 3) . '-' . substr($s, 6);
}
substr ?
if(strlen($s) == 10)
{
$newval.=substr($s,0,3)."-".substr($s,3,3)."-".substr($s,6,4);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow