从文本文件获取内容并保存其值 [英] Get contents from a text file and save its values

查看:69
本文介绍了从文本文件获取内容并保存其值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取一个名为 file.txt 的文本文件的内容。该文件的内容为:

I need to get the contents of a text file called file.txt. The contents of that file are:


word1,word 2,word 3 1,另一个单词1,

word1,word 2,word 3 1,another word 1,

我有一个 config.php ,其中包括:

$file = "file.txt";
$value = explode(",", $file);

script.php 文件将执行其他基于 $ value 的命令,其中包括:

And script.php file which will execute other commands based on $value which includes:

if (count(explode($value, $chat))>1) {

之后,它将执行如果在 $ chat 中检测到 $ value ,则执行命令。因此,我需要 $ value 作为 file.txt 中的单独单词。

After that, it will execute a command if the $value was detected in $chat. So, I need the $value to be a separate word in file.txt.

我该怎么做?

推荐答案

如果您需要更大的灵活性,则可以想要尝试使用 preg_split ,而不是爆炸,后者会在正则表达式上拆分。例如,要拆分换行符和逗号,可以使用以下命令:

If you're looking for more flexibility, you might want to try using preg_split rather than explode, which splits on a regular expression. For example, to split on newlines and commas, you could use this:

$text = file_get_contents('text.txt');    
$values = preg_split('/[\n,]+/', $text);

进行测试:

$s = "word1,word 2\n word 3";     
print_r(preg_split('/[\n,]+/', $s));

输出:

Array
(
    [0] => word1
    [1] => word 2
    [2] =>  word 3
)

将其放入脚本中:

$file = "file.txt";
$text = file_get_contents($file);
$values = preg_split('/[\n,]+/', $text);

然后 $ values 是一个数组,其中您可以在其他脚本中循环遍历:

Then $values is an array, which you can loop over in the other script:

foreach ($values as $value) {
    // do whatever you want with each value
    echo $value;
}

这篇关于从文本文件获取内容并保存其值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆