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