问题
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