有什么理由插入到一个由大文本(1000k+单词(1行没有'n
或'r
((组成的数组中,在随机位置使用preg_split("/'s/", $str);
另一个数组,该数组在键上包含特定单词和值多少次?
我需要在文本单词和需要插入的单词之间声明一个字距。
一个例子来理解我一直在说什么:这是添加之前的文本:
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
)
这是这样的话:
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
)
这是添加后的文本:
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
)
foreach ($newWords as $newWord => $count) {
for ($i = 1; $i <= $count; $i++) {
array_splice($allWords, mt_rand(0, count($allWords)-1), 0, $newWord);
}
}
如果我正确理解你需要什么,您可以在拆分文本后使用array_count_values:
$splitResult = array("Lorem","word2","ipsum","dolor","sit","word1","amet","word1");
$newArray = array_count_values($splitResult);
现在,数组键是单词,数组值是文本中的单词数:
foreach ($newArray as $key => $value) {
echo "$key - <strong>$value</strong> <br />";
}
希望对您有所帮助
简单用法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
)