首页 > 解决方案 > 我怎样才能只将我的 php 代码中的非重复数据保存到 txt 文件中?还是仅显示内容旋转中的非重复内容?

问题描述

我想将我随机创建的数据保存在 txt 文件中,但只保留非重复数据,并且只在浏览器上显示非重复数据我如何在 PHP 中做到这一点?

我尝试使用内容旋转代码创建不同的句子;但是我遇到了 2 个问题,第一个问题是我的代码无法显示不重复的句子,当我想将它们保存到 txt 文件中时,他只取 1 个句子而不写其他句子。

这是我的代码:

<?php

function RandomContent($txt)
{

    $pattern = '#\{([^{}]*)\}#msi';
    $test = preg_match_all($pattern, $txt, $out);

    $toFind = array();
    $toReplace = array();

    foreach ($out[0] as $id => $match) {
        $choices = explode("~", $out[1][$id]);
        $toFind[] = $match;
        $toReplace[] = trim($choices[rand(0, count($choices) - 1)]);
    }

    return str_replace($toFind, $toReplace, $txt);
}

    $role1= "{hero~king~president}";
    $role2="{warrior~soldier~pilote}";
    $text =  "\n" . "i'm not a ". $role1 . " but i'm a " . $role2;
   $numberOfSentences= 10;

    for ($i = 0; $i <= $numberOfSentences - 1; $i++) {

            echo "<pre>";
            echo RandomContent($text);

            $texttoregistry = RandomContent($text);

            file_put_contents('Random4.txt', $texttoregistry, FILE_APPEND);
            echo " || your data is registry into the ramdon file txt";



    }
    $lines = file('Random4.txt');
    $lines = array_unique($lines);

我尝试了几件事,第一次尝试使用 FILE_APPEND 保存我使用 ramdon 函数创建的所有行

并从 Random4.txt 中删除它们,我使用 array_unique 但这不起作用。

这是我的 Random4.txt 和浏览器中的结果:

i'm not a hero but i'm a soldier
i'm not a hero but i'm a pilote
i'm not a hero but i'm a warrior
i'm not a hero but i'm a pilote
i'm not a king but i'm a warrior
i'm not a president but i'm a pilote
i'm not a king but i'm a soldier
i'm not a king but i'm a soldier
i'm not a king but i'm a pilote

我期望的是这样的:

i'm not a hero but i'm a soldier
i'm not a hero but i'm a warrior
i'm not a hero but i'm a pilote
i'm not a king but i'm a soldier
i'm not a king but i'm a warrior
i'm not a king but i'm a pilote
i'm not a president but i'm a soldier
i'm not a president but i'm a warrrior
i'm not a president but i'm a pilote

有人不能引导我找到解决方案吗?提前谢谢你

标签: phpduplicatessave

解决方案


推荐阅读