在随机位置插入数组随机字

时间:2014-08-24 11:00:17

标签: php arrays random

是否有任何原因要插入到一个大文本(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
 )

3 个答案:

答案 0 :(得分:1)

如果我理解你需要什么, 拆分文本后可以使用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 />"; 
}

我希望你有所帮助

答案 1 :(得分:1)

foreach ($newWords as $newWord => $count) {
    for ($i = 1; $i <= $count; $i++) {
        array_splice($allWords, mt_rand(0, count($allWords)-1), 0, $newWord);
    }
}

答案 2 :(得分:1)

简单使用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
)