考虑像这样的txt文件
@[111:a]@[222:a]@[333:a]
@[444:a]@[555:a]@[666:a]
@[777:a]@[888:a]@[999:a]
我想以这样的方式加扰它:@ [和:a]之间的值随机重新排序,如下例所示:
@[777:a]@[555:a]@[999:a]
@[444:a]@[222:a]@[888:a]
@[111:a]@[666:a]@[333:a]
答案 0 :(得分:2)
$file = <<<EOF
@[111:a]@[222:a]@[333:a]
@[444:a]@[555:a]@[666:a]
@[777:a]@[888:a]@[999:a]
EOF;
preg_match_all('/@\[[^\]]+\]/', $file, $matches);
shuffle($matches[0]);
echo join(PHP_EOL, array_map('join', array_chunk($matches[0], 3)));
它基本上只是将所有项目解析为一个数组,对数组进行混洗,然后每行再输出三个。
答案 1 :(得分:1)
<?php
$content = '';
preg_match_all("/@\[[0-9]+\:a\]/", file_get_contents("file.txt"), $matches);
$matches = $matches[0];
shuffle($matches); //shuffle array's order
foreach($matches as $match) {
$content .= $match;
}
file_put_contents("file.txt", $content);
?>
请注意,您可能会收到权限错误。
答案 2 :(得分:0)
您可以使用]
在explode()
上拆分整个内容,但需要将]
追加到每个元素上。将数组洗牌然后再次输出。
$string = file_get_contents('file.txt');
// Split into an array on the right bracket, and strip out line breaks.
$array = explode("]", str_replace("\n", "", $string));
// Shuffle it
shuffle($array);
$output = "";
// Iterate over the array assembling it back into a string
$len = count($array);
for ($i = 0; $i < $len; $i++) {
// Don't forget to add the right bracket back on
$output .= $array[$i] . "]";
// Linebreak every 3rd element.
if ($i % 3 == 0) $output .= "\n";
}
// Write out to file
file_put_contents("output.txt", $output);
答案 3 :(得分:0)
如何分解并随机化订单?
$contents = file_get_contents('thefile.txt'); //read file contents
$parts = explode('@', $contents); //split it into an array by its @ character
shuffle($parts); //shuffle the array
$result = ""; //create a base string
$i = 0; //counter
foreach($parts as $part)
{
$part = trim($part); //Remove any spaces before or after string part.
$result .= '@'.$part; //add it to the result with the @ again.
$i++;
if($i % 3 >= 3) //If we are over a 3rd one we insert a new line
$result .="\r\n";
}
file_put_contents('destination.txt', $result); //Save the file
答案 4 :(得分:0)
$input = '@[111:a]@[222:a]@[333:a]
@[444:a]@[555:a]@[666:a]
@[777:a]@[888:a]@[999:a]';
// parse input
preg_match_all('/@\[[0-9]+:a]/', $input, $matches);
$matches = $matches[0];
// randomise
shuffle($matches);
// create output
$output = '';
$columns = 0;
foreach ($matches as $match) {
$output .= $match;
$columns++;
if ($columns == 3) {
$output .= "\n";
$columns = 0;
}
}
// print output as html
print nl2br($output);