Get contents from a text file and save its values

纵然是瞬间 提交于 2020-01-17 04:25:35

问题


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,another word 1,

I have a config.php which includes:

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

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

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

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.

How can I do this?


回答1:


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);

Testing it out:

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

Output:

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

Putting that into your script:

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

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;
}



回答2:


Reading file contents:

file_get_contents

Explode string:

explode

Get file as array (each line => one item):

file

BTW: a short google would already answer your question...




回答3:


In config.php add this code, be sure that the file is in the same folder

$value = file_get_contents('file.txt');

Then in script.php add this code:

$pieces = explode(",", $value);

Read more about file_get_contents and explode. (Click on the names)



来源:https://stackoverflow.com/questions/25161372/get-contents-from-a-text-file-and-save-its-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!