Reputation: 210
Is there any why to insert into an array that whas maked from a big text (1000k+ words(1 row no \n
or \r
)) using preg_split("/\s/", $str);
in random position another array that contains on key the specific word and the value how many times ?
I need to declare a wordspacing betwen the text words and the words that need to be inserted.
An example to understand what i have been saying: This is the text before adding:
Array
(
[0] => Lorem
[1] => ipsum
[2] => dolor
[3] => sit
[4] => amet,
[5] => consectetur
[6] => adipisicing
[7] => elit,
[8] => sed
[9] => do
[10] => eiusmod
[11] => temporincididunt
[12] => ut
[13] => labore
[14] => et
)
This are the words:
Array
(
[word1] => 2 // like i sayed word1 is the word that needs inserted and 2 is how many times
[word2] => 3 // like i sayed word2 is the word that needs inserted and 3 is how many times
)
This is the text after added:
Array
(
[0] => Lorem
[1] => word2
[2] => ipsum
[3] => dolor
[4] => sit
[5] => word1
[6] => amet,
[7] => consectetur
[8] => adipisicing
[9] => elit,
[10] => word1
[11] => sed
[12] => do
[13] => eiusmod
[14] => word2
[15] => temporincididunt
[16] => ut
[17] => labore
[18] => word2
[19] => et
)
Upvotes: 0
Views: 252
Reputation: 3928
simple use array_count_values
http://php.net/manual/de/function.array-count-values.php
$array = array("foo","bar","foo","baz","foo","baz");
$counts = array_count_values($array);
print_r($counts);
Array
(
[foo] => 3
[bar] => 1
[baz] => 2
)
Upvotes: 1
Reputation: 212412
foreach ($newWords as $newWord => $count) {
for ($i = 1; $i <= $count; $i++) {
array_splice($allWords, mt_rand(0, count($allWords)-1), 0, $newWord);
}
}
Upvotes: 1
Reputation: 672
if I understand correctly what you need, you can use array_count_values after split the text:
$splitResult = array("Lorem","word2","ipsum","dolor","sit","word1","amet","word1");
$newArray = array_count_values($splitResult);
now, the array key is the word and the array value is the number of words in your text:
foreach ($newArray as $key => $value) {
echo "$key - <strong>$value</strong> <br />";
}
I hope you helpful
Upvotes: 1