Jump to content

Recommended Posts

Hi all,

 

I need to extract every second word in a string:

 

eg: $foo = "one two three four five six"

 

I need $bar to only consist of every other word like this:

 

$bar = "one three five"

 

How might I do this, also any code examples would be much appreciated.

 

:)

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!

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.