budimir Posted November 22, 2013 Share Posted November 22, 2013 Guys can any one tell me how to format a string to look like this: Original string: 531008058 Wanted string: 531 00 80-58 I can't find a proper solution... Thank you! Quote Link to comment Share on other sites More sharing options...
requinix Posted November 22, 2013 Share Posted November 22, 2013 Always nine digits? I'd take the easy way out: substr($string, 0, 3) . " " . substr($string, 3, 2) . " " . substr($string, 5, 2) . "-" . substr($string, 7, 2) Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted November 22, 2013 Solution Share Posted November 22, 2013 Some years ago I wrote myself a general purpose utility function for formatting strings (part numbers, phone numbers etc) function formatIt($format,$str) { $i = $j = 0; $res = ''; $kf = strlen($format); $ks = strlen($str); while ($i < $kf && $j < $ks) { $res .= $format[$i]=='#' ? $str[$j++] : $format[$i]; ++$i; } if ($j<$ks) $res .= substr($str,$j); return $res; } $str1 = '531008058'; echo formatIt('### ## ##-##', $str1); // --> 531 00 80-58 // or phone numbers eg $str2 = '01234567890222'; echo formatIt('(####) ### #### ext ###', $str2); // --> (0123) 456 7890 ext 222 Quote Link to comment Share on other sites More sharing options...
budimir Posted November 22, 2013 Author Share Posted November 22, 2013 Barand, exactly what I need!!! Thank you so much! Very usefull for other things. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.