PHP字符串以单词开头键入数组


PHP String into array keyed by word start

假设我有以下字符串

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

创建一个数组的最佳解决方案是什么?数组键是单词开头的字符串计数?

$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";

简单如下:

str_word_count($str, 2);

str_word_count()的作用是

str_word_count()--返回字符串中使用的单词信息

str_word_count(),第二个参数为2,以获取偏移量;您可能需要使用第三个参数来包括单词

中的连字符和字母
$str = "once in a great while a good-idea turns great";
print_r(str_word_count($str, 2));

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

试试这个:

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

编辑:刚刚看到马克·贝克的回答。可能是比我更好的选择!

您可以使用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];
}