strtok()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ibolui
Forum Commoner
Posts: 27
Joined: Thu May 26, 2005 9:41 am

strtok()

Post by ibolui »

hi, i cant get strtok() to work :oops: someone helps? thanks

Code: Select all

$str = &quote;a@b@c#d@e@f#g@h@i&quote;;
$temp = strtok($str,&quote;#&quote;);
while($temp) {
	echo &quote;temp = &quote;.$temp.&quote;<br>&quote;;
	$tok = $temp;
	$tok = strtok($tok,&quote;@&quote;);
	while($tok) {
		echo &quote;tok is &quote;.$tok.&quote;<br>&quote;;
		$tok = strtok(&quote;@&quote;);
	}
	$temp = strtok(&quote;#&quote;);
}
output is...
temp = a@b@c
tok is a
tok is b
tok is c

but i wanted a b c d e f g h i // each chars on a new line
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

I think strtok is getting confused because you're calling it on two different strings. Try explode()

Code: Select all

$each_line = explode($str,&quote;#&quote;);
foreach(entry in $each_line)
{
  $words_in_line = explode($each_line,'@');
  foreach(entry in $words_in_line)
  {
   echo word
  }
}
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

I guess this is to easy, but you didn't claim that the string would change, so... I can only answer what I can read.

Code: Select all

<pre>
<?php
$str = "a@b@c#d@e@f#g@h@i";
for ($i = 0; $i < strlen($str); $i += 2) {
    echo $str{$i}."\n";
}
?>
ibolui
Forum Commoner
Posts: 27
Joined: Thu May 26, 2005 9:41 am

Post by ibolui »

the string will change :)
but thanks!
Post Reply