point86 Posted March 12, 2007 Share Posted March 12, 2007 Hi, I have a string, "$string1" the contents of which is, say, "ARTWISKXJAMAKFPXIO" Now I need a loop that reads through the string, and after every two characters, makes a space. Thus, the resultant output will be $string1afterwards = "AR TW IS KX JA MA KF PX IO" Any ideas? Thanks P86. Quote Link to comment Share on other sites More sharing options...
peeps Posted March 12, 2007 Share Posted March 12, 2007 You may be able to simplify this a little. but the basic idea is there. $string1 = "ARTWISKXJAMAKFPXIO"; $newstring= ""; $i =0; while ($i < strlen($string1)) { //echo substr($string1, $ $newstring .= substr($string1,$i,2); $newstring .= " "; $i +=2 ; echo "$i <br>"; } echo $newstring; Quote Link to comment Share on other sites More sharing options...
Barand Posted March 12, 2007 Share Posted March 12, 2007 <?php $str = "ARTWISKXJAMAKFPXIO"; $result = ''; for ($i=0, $l=strlen($str); $i<$l; $i++) { $result .= $str{$i}; if ($i%2) $result .= ' '; } echo $result; ?> or (PHP5 only) <?php $str = "ARTWISKXJAMAKFPXIO"; $a = str_split($str, 2); echo join (' ', $a); ?> Quote Link to comment Share on other sites More sharing options...
point86 Posted March 16, 2007 Author Share Posted March 16, 2007 Ok thanks, this works fine: I've split the string successfully. Now if the string was made up of ASCII characters (eg 66 67 68 69), how do I get the system to convert these into normal character values (eg B C D E)? Thanks P86. Quote Link to comment Share on other sites More sharing options...
peeps Posted March 16, 2007 Share Posted March 16, 2007 Give these two functions a try. printf("%c%c%c%c", 66, 67, 68, 69); //or $var = chr(66); Hope that helped. Quote Link to comment Share on other sites More sharing options...
point86 Posted March 16, 2007 Author Share Posted March 16, 2007 Thanks, that's fantastic Point. 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.