Jump to content

[SOLVED] Extract every second word in a string?


ghostwalkz

Recommended Posts

http://be.php.net/manual/en/control-structures.for.php

http://be.php.net/manual/en/control-structures.if.php

http://be.php.net/substr

http://be.php.net/strlen

 

if you understand those you know how to do it

 

if not,

loop trough every character in the string

if the character is a " " (space) you know the next word begins

add a counter that counts wich word you're at

add more counters to know where the word starts and ends

add the words you need to the new string

$foo = "one two three four five six";
$arr = explode( ' ', $foo );
for( $i = 0; $i < count( $arr ); $i++ )
  if( $i % 2 == 0 )
    echo $arr[$i].' ';

I keep messing up variables lately, working in PHP, javascript and java all at once makes you mess up a lot of things.. not to speak of my own mistakes, code above is tested and actually works ;)

And here's my version: (just thought I add some new flavor into this)

 

$foo = 'one two three four five';

$tok = $bar = strtok($foo, ' ');
while (strtok(' ') !== false && ($next = strtok(' ')) !== false) $bar .= ' ' . $next;

var_dump($bar);

 

 

Now thats what I am talking about!!! TY!!! Fixed!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.