Blake
Blake

Reputation: 263

PHP String into array keyed by word start

Say I have the following string

$str = "once in a great while a good-idea turns great";

What would be the best solution to creating an array with the array key being the string count of where the word(s) starts?

$str_array['0'] = "once";
$str_array['5'] = "in";
$str_array['8'] = "a";
$str_array['10'] = "great";
$str_array['16'] = "while";
$str_array['22'] = "a";
$str_array['24'] = "good-idea";
$str_array['34'] = "turns";
$str_array['40'] = "great";

Upvotes: 5

Views: 133

Answers (5)

ficuscr
ficuscr

Reputation: 7054

As simple as the following:

str_word_count($str, 2);

what str_word_count() does is

str_word_count() — Return information about words used in a string

Upvotes: 10

Green Black
Green Black

Reputation: 5084

$str = "once in a great while a good-idea turns great";
print_r(str_word_count($str, 2));

demo: http://sandbox.onlinephpfunctions.com/code/9e1afc68725c1472fc595b54c5f8a8abf4620dfc

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227270

You can use preg_split (with the PREG_SPLIT_OFFSET_CAPTURE option) to split the string on the space, then use the offset it gives you to make a new array.

$str = "once in a great while a good-idea turns great";
$split_array = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);

$str_array = array();

foreach($split_array as $split){
    $str_array[$split[1]] = $split[0];
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Try this:

$array = preg_split("/ /",$str,-1,PREG_SPLIT_OFFSET_CAPTURE);
$str_array = Array();
foreach($array as $word) $str_array[$word[1]] = $word[0];

EDIT: Just saw Mark Baker's answer. Probably a better option than mine!

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212422

str_word_count() with 2 as the second argument to get the the offset; and you'd probably need to use the 3rd argument to include hyphen as well as letters in words

Upvotes: 7

Related Questions