Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP String into array keyed by word start

Tags:

php

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";
like image 705
Blake Avatar asked Feb 05 '13 17:02

Blake


People also ask

How do you insert an item at the beginning of an array in PHP?

The array_unshift() function inserts new elements to an array. The new array values will be inserted in the beginning of the array.

How can I get the first 5 characters of a string in PHP?

You can use the substr function like this: echo substr($myStr, 0, 5);

How do I add characters to the beginning of a string in PHP?

There is no specific function to prepend a string in PHP. But you can use the PHP concatenation operator ( . ) to prepened a string with another string.


1 Answers

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

like image 54
ficuscr Avatar answered Oct 12 '22 23:10

ficuscr