如何使用分解函数来分隔和显示不同的值


How to use explode function to delimit and display different values

我正在为我的英语课制作一个随机句子生成器。我很接近,但由于我的 php 和 javascript 知识有限,我需要寻求帮助。我不擅长阅读代码,我只是在编写代码时陷入困境。

我想使用爆炸来分解一串逗号分隔的值。字符串是英语和西班牙语的混合,在.txt文件中,它们将分开,如下所示:

The book, El libro
The man, El hombre
The woman, La mujer

等。

我想将这两个值分解成一个数组,并将它们显示在我网页上的不同位置。我将使用我发现的随机文本生成器脚本,它运行良好,没有问题。我只需要使用 explode 对其进行修改即可读取,将值分隔到数组中,并能够显示数组的单独值。

<?php
/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';
/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;
/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;
// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}
 // Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}
// If we have any text choose a random one, otherwise show 'No text to                              choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
 }
// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("'n","'r"),'',$txt);
// Set the correct MIME type
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write('''.addslashes($txt).''')';
}
else
{
echo $txt;
}
?>

显示结果的脚本:

 <script type="text/javascript" src="rantex.php?type=1"></script>

有人可以帮我修改 rantex.php 文件,以便我可以使用 explode 来分隔不同的逗号分隔值,并使用不同的脚本在我的网页上的不同位置调用它们吗?

谢谢,请原谅我的菜鸟。

以下内容似乎没有必要,因为 file() 已经删除了换行符:

// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("'n","'r"),'',$txt);

要换行,您可以改用:

list($english, $spanish) = explode(', ', trim($txt));

看来您正在尝试使用 PHP 来提供带有一些随机句子的静态页面,对吧?那么为什么不使用PHP来提供有效的JSON,并使用句柄在客户端上显示逻辑呢?

这是一个快速实现。

// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);
// Build an array (break on every line break)                           
$sentences = explode("'n", $source);
// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) { 
  return $item !== "";
});
// Build a hashmap of the array
$pairs = array_map(function($item) { 
  return ['sentence' => $item];
}, $filtered);
// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);

现在你可以让客户端用一些基本的JavaScript来处理剩下的事情。

// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];
// Finally display it
random.sentence

[编辑]

您可以通过多种方式将 JSON 数据获取到客户端,但如果您不想使用 Ajax 之类的东西,您可以简单地将内容转储到您的网页上,然后使用 JavaScript 从全局窗口对象更新随机句子。

// Inside your php page
<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>
<script>
  var sentences = <?= json_encode($pairs); ?>;
  var random = sentences[Math.floor(Math.random() * sentences.length)];
  var elspa = document.getElementById('spanish');
  var eleng = document.getElementById('english');
  elspa.innerText = random.sentence.split(',')[1];
  eleng.innerText = random.sentence.split(',')[0];
</script>

好的,所以我已经弄清楚了,我拿 0 学分,因为我付钱给某人做这件事。特别感谢@stormpat把我送到正确的方向,如果不是他,我就不会从JSON的角度来看待这个问题。

这。PHP文件是这样的:

<?php
$f_contents = file('quotes.txt'); 
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];
echo json_encode($data);
?>

在页眉的.HTML页上:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
    (function ($) {
        $(function()
        {
            function load_random_data() {
                $.get('random_line.php', function(data) {
                    var data = $.parseJSON(data);
                    $('#random_english').text(data.eng);
                    $('#random_spanish').text(data.esp);
                });
            }
            load_random_data();
            $('#get_random').click(function(e){
                e.preventDefault();
                load_random_data();
            });

        });
    })(jQuery);
    </script>
这会将不同的变量拆分为类,因此

要将它们调用到我的 html 页面中,我按它们的类调用它们,例如,我想将变量放入表单元格中,因此我为单个 td 单元格提供了一个类:

                <td id="random_spanish"></td>
                <td id="random_english"></td>

另外,作为奖励,编码人员加入了一个漂亮的按钮来刷新json类:

<input type="button" value="Get random" id="get_random" />

所以现在我不必让我的学生刷新整个网页,他们只需点击按钮并刷新随机变量。

再次感谢大家!