0
$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.

2
  • What does that code do? I'm lazy to run it. Commented Dec 28, 2010 at 7:34
  • 2
    -1 for assuming we should know what that code does. Commented Dec 28, 2010 at 7:39

3 Answers 3

5

Sure, you can use substr to accomplish this:

if(strlen($s) == 10) {
   $s = substr($s, 0, 3) . '-' . substr($s, 3, 3) . '-' . substr($s, 6);
}

codepad example

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

0

substr ?

if(strlen($s) == 10)
{
   $newval.=substr($s,0,3)."-".substr($s,3,3)."-".substr($s,6,4);
}

1 Comment

You don't need the length argument on the last substr call if you already know what the length of the entire string is! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.