I found interesting problem while I was trying to achieve something simple like splitting string into array. The only difference here is that Im trying to take the string from .txt file
My code is the following:
$handle = fopen("input.txt", "r"); // open txt file
$iter = fgets($handle);
// here on first line I have the number of the strings which I will take. This will be the for loop limitation
for ($m = 0; $m < $iter; $m++)
{
$string = fgets($handle); // now getting the string
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}
This is the content of my .txt file
4
abc
abcba
abcd
cba
I tried with array_filter() and all other possible solutions/functions. Array filter and array diff are not removing the empty elements, no idea why... Also in my txt file there are no blank spaces or anything like that. Is this a bug in a str_split function ? Any logic behind this ?
The extra whitespace is a newline. Each row except the last technically contains all of the text contents you see, plus a newline.
You can easily get rid of it by e.g.
$string = rtrim(fgets($handle));
Also, fgets($fp); makes no sense since there's no variable $fp, should be fgets($handle); given your above code.
Trimming the spaces and need to change your fgets($fp) to fgets($handle) as there's no variable like of $fp.You need to update your code into as
for ($m=0;$m<$iter;$m++)
{
$string = trim(fgets($handle)); //
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}
Related
I have txt file and I need to echo specific data in a loop.
Let's say my txt file name is this: myfile.txt
and the structure inside is like this:
etc="Orange" src="stack1"
etc="Blue" src="stack2"
etc="Green" src="stack3"
etc="Red" src="stack4"
How can I echo in PHP these values: Orange, Blue, Green, Red?
you can use preg_match_all for this:
<?php
# get your text
$txt = file_get_contents('your_text_file.txt');
# match against etc="" (gets val inside the quotes)
preg_match_all('/etc="([^"]+)"/', $txt, $matches);
# actual values = $matches[1]
$values = $matches[1];
echo '<pre>'. print_r($values, 1) .'</pre>';
$content = file_get_content("/path/to/myfile.txt", "r");
if (false === $content) {
// handle error if file can't be open or find
}
preg_match_all('/etc="(.*?)"/', $content, $matches);
echo implode($matches[1], ',');
With file_get_content you retrieve what's int he file.
After that you need to check if file_get_content has returned an error code (false in this case).
preg_match_all will use RegExp to filter out only what you need. In particular:
/ #is a delimiter needed
etc=" #will match literally the letters etc="
(.*?) #is a capturing group needed to collect all the values inside the "" part of etc value. So, capturing group is done with (). .* will match every character and ? make the quantifier "non greedy".
/ #is the ending delimiter
All matches are collected inside $matches array (is not necessary that $matches is previously defined.
Finally, you need to transform the collected values into a string and you can do this with implode function.
I exaplain all on code //comments.
<?php
$fichero = file_get_contents('./myfile.txt', false);
if($fichero === false){ //if file_get_contents() return false, the file isn't found, if its found, return data.
echo "Can't find file.\n";
}else{ //If file is find, this condition is executed.
$output = array(); //this variable is who will get the output of regular expression pattern from next line function.
preg_match_all('/([A-Z])\w+/',$fichero, $output);
for($i = 0; $i < count($output[0]); $i++){ //Iterate throught the first array inside of array of $output, count(array) is for get length of array.
echo $output[0][$i]; //Print values from array $output[0][$i]
if($i + 1 != count($output[0])){ //if not equal to length of array, add , at end of printed value of output[0][$i]
echo ', ';
}else{ //if equal to length of array, add . at end of printed value of $output[0][$i]
echo '.';
}
}
}
?>
I have a txt file of trivia questions. I have split them into 2 array indexes and are seperated with a \t. I need to print those questions to the user in order and I don't know how to display part of the array index before the first \t.
<?php
session_start();
$file = "trivQuestions.txt";
$result = file($file);
$_SESSION['question'] = array();
$_SESSION['correctAnswers'] = array();
var_dump($_SESSION['question']);
foreach ( $result as $content ) {
$question = explode("\t", $content);
// echo $question[0];
//echos all questions
var_dump($question[0]);
//echo $question[0];
//echos all answers
//echo $question[1];
}
if (isset($_POST['submit'])){
}else{
echo "Welcome to trivia! Enter your answer below.";
}
?>
As your file has a question and answer separated by a tab on each new line in the file, you will have to split your file by each new line first. After that you will be able to loop trough each line of the file and split it by a tab.
From here you could add you split into a new array or do whatever you want to do with it.
In the code below I tried to demonstrate how such a split with loop would work, according to your description.
$file = "trivQuestions.txt";
$result = file($file);
// before you split by \t, you have to split by each new line.
// this will get you an array with each question + answer as one value
// PHP_EOL stands for end of line. PHP tries to get the end of line by using the systems default one. you can adjust that, if it a specific
// linebreak like "\n" or something else you know of.
$lines = explode(PHP_EOL, $result);
// var_dump($lines); <- with this you would see that you are on the right way
// setup a questions array to fill it up later
$questions = array();
// lets loop trough the lines
foreach ($lines as $line) {
// now you can explode on tab
$entry = explode("\t", $line);
// according to you description the question comes first, the answer later split by tab
// so we fill the questions array
$questions[] = $entry[0]; // the 0 element will be the question. if you want to adress the answer, use $entry[1]. maybe you want to add this in an other array for checks?
}
// this will give you the first question
var_dump($questions[0]);
If I have missed something or misunderstood parts of your question, let me know. Maybe I can adjust this code, to make it work as you need it to be.
I have a text file and I want each line to be an element of an array.
$file = file("books.txt");
$split = explode("\n", $file);
Then if I try to print an element of the array:
echo "$split[0]";
I get no output.
Because file("books.txt") gives already an array resulting from exploding by newline, you can echo "$file[0]";, no need for further exploding.
I am trying to read a line where multiple numbers were separated by space using php. Initially I tried using fscanf however the issue is, as fscanf read one line at a time, it only reads the first number. I am confused what to do.
Sample Input
20 30 -5987 456 523
The best approach for this case is to use a combination of explode and file reading. The strategy is initially read the whole line as an string. Then use explode to store the all the number in an array. However in that case the array would a string array later on we can change the type of array element from String to integer. Here is how
<?php
$_fp = fopen("php://stdin", "r");
fscanf($_fp, "%d\n", $count);
$numbers = explode(" ", trim(fgets($_fp)));
foreach ($numbers as &$number)
{
$number = intval($number);
}
sort($numbers);
?>
$input = trim(fgets(STDIN));
$arr = explode(" ", $input);
foreach($arr as &$number){
$number = (int)$number;
}
If you want to eliminate white space from "fopen" function user "trim" function or surround variable with trim function.
Example :
echo "Please enter series limit : ";
$handles = fopen ("php://stdin","r");
$n = trim(fgets($handles));
So here we can remove white space in between the characters as well as at the end.
I want to find a word in a large list file.
Then, if and when that word is found, take the whole line of the list file that the word was found in?
so far I have not seen any PHP string functions to do this
Use a line-delimited regular expression to find the word, then your match will contain the whole line.
Something like:
preg_match('^.*WORD.*$, $filecontents, $matches);
Then $matches will have the full lines of the places it found WORD
You could use preg_match:
$arr = array();
preg_match("/^.*yourSearch.*$/", $fileContents, $arr);
$arr will then contain the matches.
$path = "/path/to/wordlist.txt";
$word = "Word";
$handle = fopen($path,'r');
$currentline = 1; //in case you want to know which line you got it from
while(!feof($handle))
{
$line = fgets($handle);
if(strpos($line,$word))
{
$lines[$currentline] = $line;
}
$currentline++;
}
fclose($handle);
If you want to only find a single line where the word occurs, then instead of saving it to an array, save it somewhere and just break after the match is made.
This should work quickly on files of any size (using file() on large files probably isn't good)
Try this one:
$searhString = "search";
$result = preg_grep("/^.*{$searhString}.*$/", file('/path/to/your/file.txt'));
print_r($result);
Explanation:
file() will read your file and produces array of lines
preg_grep() will return array element in which matching pattern is found
$result is the resulting array.