PHP String into word由word start键入

时间:2013-02-05 17:20:07

标签: php

说我有以下字符串

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

5 个答案:

答案 0 :(得分:10)

简单如下:

str_word_count($str, 2);

str_word_count()做的是

  

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

答案 1 :(得分:7)

str_word_count()以2为第二个参数来获取偏移量;你可能需要使用第三个参数来包含连字符以及单词中的字母

答案 2 :(得分:3)

$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 :(得分:2)

试试这个:

$array = preg_split("/ /",$str,-1,PREG_SPLIT_OFFSET_CAPTURE);
$str_array = Array();
foreach($array as $word) $str_array[$word[1]] = $word[0];
编辑:刚看到Mark Ba​​ker的回答。可能是比我更好的选择!

答案 4 :(得分:1)

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