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;
}
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...
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)
Related
I'm new in PHP. I'm trying to design a simple Glossary for Primary English Students.
I want to use a .txt as database, exploded by ":". I've got a txt like this:
Hola:Hello
Good Bye: Adios
Car:Coche
Banana:Plátano
Plane:Avión
By the moment I know how to print the whole text or one column, but can't print a single word:
<?php
$file = fopen("bank.txt", "r");
while(!feof($file)) {
echo fgets($file). "<br />";
}
fclose($file);
?>
How can I print only ONE SPECIFIC WORD?
e.g. What code is recquired to print only the second word of the third line?
Like mentioned in the comments... in the future you should inform yourself how to ask questions on SO.
Regarding your question, you should take a look at the explode-function and foreach-loops of PHP.
Example:
$data = 'Hola:Hello
Good Bye: Adios
Car:Coche
Banana:Plátano
Plane:Avión';
$arrData = array();
$lines = explode( "\n", $data );
foreach ($lines as $line) {
$words = explode( ":", $line );
$arrData[] = array( $words[0], $words[1] );
}
echo( $arrData[2][1] );
// Prints: "Coche"
This should work for you:
Just get your file into an array with file(). Then go through each line with array_map() and explode() the line by a : colon.
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = array_map(function($v){
return explode(":", $v);
}, $lines);
print_r($lines); //echo $lines[0][1] <- Will print the first line, second word
?>
Or what you could also do, is change your file into a .ini file format, e.g.
Hola="Hello"
Good Bye="Adios"
Car="Coche"
Banana="Plátano"
Plane="Avión"
And then you can simply use parse_ini_file(), e.g.
<?php
$file = parse_ini_file("test.ini");
//^^^^ See also here the extension
print_r($file);
?>
I am able to read from a file and create an array however I get the following error: Notice: Undefined offset: 1. Within my array there is one element that is empty and I don't understand why it is empty.
My text file is in the following format:
#EXTINF:0,ABC family USA[]http://localhost/IpInfo/index.html
#EXTINF:0,CBC[]http://localhost/IpInfo/index1.html
#EXTINF:0,A&E[]http://localhost/IpInfo/index2.html
Here is my code:
$fh = fopen('file1.txt', 'r');
$theData = fread($fh, filesize('file1.txt'));
$arr = array();
$my_array = explode("\r\n", $theData);
foreach($my_array as $line){
$tmp = explode("[]", $line);
$arr[$tmp[0]] = $tmp[1];
}
fclose($fh);
echo '<pre>';
echo print_r($arr);
I'm not quite sure what the problem is? Any help would be much appreciated!
Thanks!
Probably your input data doesn't use \r\n as the line delimiter? I'm not sure whether I got the problem completely. Also you might want to take empty lines into account.
I would use the file() function, which simplifies to iterate over the lines of a file and can handle Windows and Unix line feeds and check for empty lines:
$arr = array();
foreach(file('a.txt') as $line){
// I'm using `trim()` here since $line
// will still contain the newline delimiter
$line = trim($line);
// Skip empty lines
if(empty($line) {
continue;
}
$tmp = explode("[]", $line);
$arr[$tmp[0]] = trim($tmp[1]);
}
echo '<pre>';
print_r($arr);
Output:
<pre>Array
(
[#EXTINF:0,ABC family USA] => http://localhost/IpInfo/index.html
[#EXTINF:0,CBC] => http://localhost/IpInfo/index1.html
[#EXTINF:0,A&E] => http://localhost/IpInfo/index2.html
)
The reason is that the explode function splits your read-in data at the "\r\n". And you have a new line after the last line, and that's what results in the last "array" with no keys or values. To fix this, replace this line : $my_array = explode("\r\n", $theData); with these:
$my_array = explode("\r\n", $theData);
array_pop($my_array);
I have a directory of text files. I want to loop through each of the text files in the directory and get the overall count of unique words (count of vocabulary), not for each individual file, but for ALL the files together. In other words, I want the number of unique words within all the files together, and NOT the number of unique words for each individual file.
For example, I have three text files in a directory. Here are their contents:
file1.txt -> here is some text.
file2.txt -> here is more text.
file3.txt -> even more text.
So the count of unique words for this directory of text files in this case is 6.
I have tried to use this code:
$files = glob("C:\\wamp\\dir");
$out = fopen("mergedFiles.txt", "w");
foreach($files as $file){
$in = fopen($file, "r");
while ($line = fread($in)){
fwrite($out, $line);
}
fclose($in);
}
fclose($out);
to merge all the text files and then after using this code I planned to use the array_unique() on mergedFiles.txt. However, the code is not working.
How can I get the unique word count of all the text files in the directory in the best way possible?
You can try this :
$allWords = array();
foreach (glob("*.txt") as $filename) // loop on each file
{
$contents = file_get_contents($filename); // Get file contents
$words = explode(' ', $contents); // Make an array with words
if ( $words )
$allWords = array_merge($allWords, $words); // combine global words array and file words array
}
var_dump(count(array_unique($allWords)));
EDIT Other version which :
remove dots
remove multiple spaces
match word if missing space between end of sentence and new one.
function removeDot($string) {
return rtrim($string, '.');
}
$words = explode(' ', preg_replace('#\.([a-zA-Z])#', '. $1', preg_replace('/\s+/', ' ',$contents)));
$words = array_map("removeDot", $words);
Unless you have legitimate reasons not to simply concatenate the files and process their content as a concatenated string, use this snippet to target txt files in a directory, join their texts, make the text lowercase, isolate words, remove duplicates, then count unique words:
Code (not fully tested on a filesystem): (Demo)
echo count(
array_unique(
str_word_count(
strtolower(
implode(
' ',
array_map(
'file_get_contents',
glob("*.txt")
)
)
),
1
)
)
);
Assuming texts from file:
[
'here is some text.',
'here is more text.',
'even more text.'
]
The output is 6 from a unique array of:
array (
0 => 'here',
1 => 'is',
2 => 'some',
3 => 'text',
6 => 'more',
8 => 'even',
)
Modify the snippet as needed: perhaps use a different technique/algorithm to identify "words", or use mb_strtolower(), or don't use strtolower() at all.
I am trying to replace multiple parts of a string in a file with file_put_contents.
Essentially what the function does is finds a particular phrase in the file (which are in the $new and $old arrays and replaces it.
$file_path = "hello.txt";
$file_string = file_get_contents($file_path);
function replace_string_in_file($replace_old, $replace_new) {
global $file_string; global $file_path;
if(is_array($replace_old)) {
for($i = 0; $i < count($replace_old); $i++) {
$replace = str_replace($replace_old[$i], $replace_new[$i], $file_string);
file_put_contents($file_path, $replace); // overwrite
}
}
}
$old = array("hello8", "hello9"); // what to look for
$new = array("hello0", "hello3"); // what to replace with
replace_string_in_file($old, $new);
hello.txt is: hello8 hello1 hello2 hello9
Unfortunately it outputs: hello8 hello1 hello2 hello3
So it outputs only 1 change when it should have outputted 2:
hello0 hello1 hello2 hello3
That's a single file, so why output it after every replacement? Your workflow should be
a) read in file
b) do all replacements
c) write out modified file
In other words, move your file_put_contents() to OUTSIDE your loop.
As well, str_replace will accept arrays for its "todo" and "replacewith" arrays. There's no need to loop over your inputs. so basically you should have
$old = array(...);
$new = array(...);
$text = file_get_contents(...);
$modified = str_replace($old, $new, $text);
file_put_contents($modified, ....);
Your main problem is that your str_replace, as you wrote it, is never using the updated string. You constantly use the same ORIGINAL string for each replacement,
$replace = str_replace($replace_old[$i], $replace_new[$i], $file_string);
^^^^^^^^^^^---should be $replace
You're not updating $file_string with each iteration. I.e., you set it once at the start of the loop, replace the first pair, and then the second call to replace uses the original $file_string again.
what is the best way of extracting multiple (~40 values) from a text file using php?
the data is more or less like:
NAMEA valuea
NAMEB valueb
I'm looking for a proper* approach to extracting this data into a data-structure, because i will need to specify regexs for all of them (all 40).
did i make myself clear?
*meaning, the default/painful method would be for me to do:
$namea = extractfunction("regexa", $textfilevalue);
$nameb = extractfunction("regeb", $textfilevalue);
... 40 times!
The lines may not be in the same order, or be present in each file. Every NAMEA is text like: "Registration Number:", or "Applicant Name:" (ie, with spaces in what i was calling as NAMEA)
Response to the Col.
i'm looking for a sensible "way" of writing my code, so its readable, modifiable, builds an object/array thats easily callable, etc... "good coding style!" :)
#Adam - They do actually... and contain slashes as well...
#Alix - Freaking marvelous man! THat was GOOD! would you also happen to have any insights on how I can "truncate" the rsultant array by removing everything from "key_x" and beyond? Should i open that as a new question?
Here is my take at it:
somefile.txt:
NAMEA valuea
NAMEB valueb
PHP Code:
$file = file_get_contents('./somefile.txt');
$string = preg_replace('~^(.+?)\s+(.+?)$~m', '$1=$2', $file);
$string = str_replace(array("\r\n", "\r", "\n"), '&', $string);
$result = array();
parse_str($string, $result);
echo '<pre>';
print_r($result);
echo '</pre>';
Output:
Array
(
[NAMEA] => valuea
[NAMEB] => valueb
)
You may also be able to further simplify this by using str_getcsv() on PHP 5.3+.
EDIT: My previous version fails for keys that have spaces like #Col. Shrapnel noticed. I didn't read the question with enough attention. A possible solution since you seem to be using keys that always have : appended is this:
$string = preg_replace('~^(.+?):\s+(.+?)$~m', '$1=$2', $file);
To remove everything from key_x to the end of the file you can do something like this:
$string = substr($string, 0, strpos($string, 'key_x'));
So the whole thing would look like this:
somefile.txt:
Registration Number: valuea
Applicant Name: valueb
PHP Code:
$file = file_get_contents('./somefile.txt');
$string = substr($file, 0, strpos($file, 'key_x'));
$string = preg_replace('~^(.+?):\s+(.+?)$~m', '$1=$2', $string);
$string = str_replace(array("\r\n", "\r", "\n"), '&', $string);
$result = array();
parse_str($string, $result);
echo '<pre>';
print_r($result);
echo '</pre>';
Output:
Array
(
[Registration_Number] => valuea
[Applicant_Name] => valueb
)
as far as I get it you can use file() to get an array of strings and then parse these strings with some regexp.
if you add a = sign between names and values, you'll be ble to get the whole thing at once using parse_ini_file()
Assuming your keys (namea, nameb) never have spaces in them:
$contents = file('some_file.txt'); // read file as array
$data = array();
foreach($contents as $line) { // iterate over file
preg_match('/^([^\s]+)\s+(.*)/', $line, $matches); // pull out key and value into $matches
$key = $matches[1];
$value = $matches[2];
$data[$key] = $value; // store key/value pairs in $data array
}
var_dump($data); // what did we get?