willpower Posted July 24, 2008 Share Posted July 24, 2008 Splitting $strings if i dont have a needle, only a haystack... how do i effectrively split: abcdefghi to ---- ab cdef g hi or 123456789 to ---- 12 3456 7 89 Thanks Will Quote Link to comment Share on other sites More sharing options...
tibberous Posted July 25, 2008 Share Posted July 25, 2008 substr Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted July 25, 2008 Share Posted July 25, 2008 example: $str = '123456789'; $s = array(2, 4, 1, 2); $c = 0; foreach($s as $o) { echo substr($str, $c, $o) . ' '; $c += $o; } Quote Link to comment Share on other sites More sharing options...
Barand Posted July 25, 2008 Share Posted July 25, 2008 here's a formatting function I wrote a while ago <?php function format_template($str, $template) { $str = str_replace(' ', '', $str); $kt = strlen($template); $ks = strlen($str); $res = ''; $j = 0; for($i=0; $i<$kt; $i++) { if ($j==$ks) break; switch ($c = $template{$i}) { case '#': $res .= $str{$j++}; break; case '!': $res .= strtoupper($str{$j++}) ; break; default: $res .= $c; break; } } return $res; } /** * try it */ echo format_template ('0232892357', '## #### ####'); // --> 02 3289 2357 echo '<br />'; echo format_template ('12345678901234', '(###) ###-#### ext ####'); // --> (123) 456-7890 ext 1234 echo '<br />'; echo format_template ('07123456789', '+44 (#)### ### ####'); // --> +44 (0) 7123 456 789 echo '<br />'; echo format_template ('ab123456x', '!! ## ## ## !'); // --> AB 12 34 56 X ?> For your example echo format_template ('123456789', '## #### # ##''); 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.