Hi all,

After searching the forum for an anwser I could not find one, please I need help.

I want to format a string.

The code below works geart; it output a value of "1843341190" as "1 84334 118 2".

function formatStr2($str) { 
    return $str{0} . "-" 
        . substr($str, 1, 6) . "-" 
        . substr($str, 7, 2) . "-" 
        . $str{9}; 
}

Now I need to format another string with a value of "333155555 331"as "333 1 55555 333 1". The code I am using is:

function formatStr3($str) { 
return $str{0} . "-" 
. substr($str, 3, 3) . "-" 
. substr($str, 1 1) . "-" 
. substr($str, 5, 5) . "-" 
. substr($str, 3, 3) . "-" 
. substr($str, 1, 1) . "-" 
. $str{13}; 
}

But the results are rubbish, like:-"3---33---55---3-3"

Can someone help with this please.

    the parameters to substr are start and length. That would suggest that each subsequent call to substr needs to have a higher start value than the previous one.

      <?php
      
      $string = '333155555 3331';
      $formatted = sprintf(
         '%03d %1d %05d %03d %1d',
         substr($string, 0, 3),
         substr($string, 3, 1),
         substr($string, 4, 5),
         substr($string, 10, 3),
         substr($string, -1)
      );
      echo $formatted; // outputs "333 1 55555 333 1"
      

        Hi NogDog.

        Many thanks for your input. I need to learn from this. Your code work great.

        Can you explain what the

        '%03d %1d %05d %03d %1d',

        does and how it interacts with the rest of the function.

        Many thanks again.

          You could probably get away with just using "%s" for each sprintf() place-holder, but I figured I'd be as specific as possible.

            Write a Reply...