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 Link to comment https://forums.phpfreaks.com/topic/116506-solved-123456789-to-12-3456-7-89/ Share on other sites More sharing options...
tibberous Posted July 25, 2008 Share Posted July 25, 2008 substr Link to comment https://forums.phpfreaks.com/topic/116506-solved-123456789-to-12-3456-7-89/#findComment-599196 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; } Link to comment https://forums.phpfreaks.com/topic/116506-solved-123456789-to-12-3456-7-89/#findComment-599692 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', '## #### # ##''); Link to comment https://forums.phpfreaks.com/topic/116506-solved-123456789-to-12-3456-7-89/#findComment-599779 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.