PHP string to an array introduced by running a word

Say I have the following line

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

What would be the best solution to create an array with the array key being the string where the word (s) begins?

$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";
+5
source share
5 answers

The easiest thing is the following:

str_word_count($str, 2);

what str_word_count()is

str_word_count() - returns information about the words used in the string

+10
source

str_word_count () with 2 as the second argument to get the offset; and you probably need to use the third argument to include a hyphen, as well as letters in words

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

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

+3

:

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

: . , , !

+2

preg_split ( PREG_SPLIT_OFFSET_CAPTURE), , , .

$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];
}
+1
source

All Articles