Last line and char of text file - php

I want to display the last chars from a textfile. The textfile is from a temperature 1-wire system. The file is sometimes big. I display the last line with this:
<?php
$file = file("file.txt");
for ($i = count($file)-1; $i < count($file); $i++) {
echo $file[$i] . "\n";
}
?>
It works great!
But how do I read the last 5 chars of that line? I want to and echo them in to a div on an html-page?
regards
Anders

Try below in for loop
echo substr($file[$i], -5) . "\n";
More Info: PHP Manual

You can use substr() passing a negative value for the start argument.
echo "last 5 chars: " . substr($file[$i], -5);
From the docs:
If start is negative, the returned string will start at the start'th character from the end of string.

Thanks for your help!
I now read, round and display the temperature with this PHP:
<?php
$file = file("file.txt");
for ($i = count($file)-1; $i < count($file); $i++) {
echo round(substr($file[$i], -5) . "\n", 1);
}
However problem when there is more or less characters.
Is there a way to read the last characters after the semicolon on the last line?
Three examples:
07.07.2012; 06:19:23;25.63 - display 25.6
09.12.2012; 06:19:23;-5.63 - display -5.6
12.09.2012; 22:58:49;-17.86 - display -17.9
regards
Anders

Related

Counting vowels in a text file with PHP

I'm trying to count the vowels in a lengthy text, provided by a .txt file. I can successfully open the file and echo it out into the browser. What I can't seem to do is get my script to do the actual vowel counting and I'm not entirely sure why. I'm supposed to output the vowel count to a file that doesn't previously exist, but is referred to as "file_output1.txt". I'm not sure if this is what is causing the issue, or if I'm not properly accessing the text file (Assignment Input) to enable the count to occur, or if I made a syntax error my eyes just can't seem to catch right now.
This is what I've done so far, but I'm not getting the count to fill. There are hundreds of vowels in the text file and it keeps spitting out: "There are (0) vowels". I have counted letters in a string before, but I am having trouble doing it with the file. Any advice?
<?php
#openfile
$file = "Assignment2inputfile.txt" ;
$document = fopen($file,r);
echo fread($document,filesize("Assignment2inputfile.txt"));
?>
<html>
<br><br>
</html>
<?php
#vowelcount
$vowels = array("a", "e", "i", "o", "u");
$length = strlen($_POST["file_output1.txt"]);
$count = 0;
for ($i =0; $i = $length; $i++)
{
if (array_search($_POST["file_output1.txt"][$i], $vowels))
{
$count++;
}
}
echo 'There are (' . $count . ') vowels ' . $_POST["file_output1.txt"] .'.';
fclose($document);
?>
I have counted letters before, but this time it is not a short string input. How can I do this for vowels, but with a FILE instead of a string?
You could use a regex to do this quite simply
$text='The quick brown fox jumped over the lazy dog';
$pttn='#[aeiouAEIOU]#';
preg_match_all( $pttn, $text, $matches );
printf( '<pre>%s</pre>',print_r( $matches, true ) );
printf('There are %d vowels',count($matches[0]));
The array_search is meant for finding a key of a value inside an array. But, you want to count the number of vowels in a string.
Since you have already read the entire file into memory, one simple approach here would be to just strip all vowels, and then compare the length of the resulting string against the original length:
$text = $_POST["file_output1.txt"];
$length = strlen($text);
$new_text = preg_replace("/[aeiou]/i", "", $text);
echo "Number of vowels: " . ($length - strlen($new_text));
Here is a brief demo showing that the above logic is working:
Demo
Here, I have updated code.
<?php
$file = "Assignment2inputfile.txt";
$document = fopen($file, 'r');
$output = fread($document, filesize("Assignment2inputfile.txt"));
$vowels = array(
"a",
"e",
"i",
"o",
"u"
);
$length = strlen($output);
$count = 0;
for ($i = 0; $i < $length; $i++) {
if (array_search($output[$i], $vowels)) {
$count++;
}
}
echo 'There are (' . $count . ') vowels ' . $count . '.';
fclose($document);
?>
I don't quite understand, are you trying to echo the file then read it via $_POST ???. That wouldn't work. If you're using a single php file then try
$file = "Assignment2inputfile.txt" ;
$document = fopen($file,r);
$str = fread($document,filesize("Assignment2inputfile.txt"));
Now you can use $str as
$vowels = array("a", "e", "i", "o", "u");
$length = strlen($str);
$count = 0;
for ($i =0; $i = $length; $i++)
{
if (array_search($str[$i], $vowels))
{
$count++;
}
}
finally write it to required file.
P.S I haven't completely understood your question but this should help if you're trying a normal read from a local file.
Based on this:
I'm trying to count the vowels in a lengthy text, provided by a .txt
file[...] I have counted letters in a string before, but I am having
trouble doing it with the file. Any advice?
You can use the following line of code to count only vowels in a file
str_ireplace(['a','e','u','i','o'],' ',file_get_contents('Assignment2inputfile.txt'),$count);
We basically simulate an insensitive case replacement while keeping track of the number of replacements which give exactly what you need the number of vowels
Then based on this:
I'm supposed to output the vowel count to a file that doesn't
previously exist, but is referred to as "file_output1.txt".
file_put_contents("file_output1.txt",sprintf('There are %d vowels ',$count));
we use this line of code to create a new file if not exists and put a formatted string with the number of vowels as expected.
First possibility that you are sending $_POST['file_output1.txt'] from another file to here displayed file.
if you are not getting any POST data or All you have is here displayed sample file, then my friend you are wrong, you have to take form and form fields like text-field, textarea etc,
and you have to submit it at here displayed file with post request so you can take $_POST variable, i am assuming that you are doing right then your code is fine except it has 2 errors like below:
Notice: Use of undefined constant r - assumed 'r' in C:\xampp\htdocs\stackplay\count_vowels.php on line 4
You have used (file operation mode) r in fopen($file,'r') function without quote , it should be in single or double quote
see the syntax here fopen (string $filename , string $mode)
second error is logical error in for loop You have written for ($i =0; $i = $length; $i++) so it will assign length of file content to $i in first iteration and loop runs infinitely still occur execution time out or allocated memory exhausts, so to solve it replace it with for ($i =0; $i < $length; $i++)
Second Possibility that you are not getting any POST data or All you have is file displayed in sample code in question, then i am giving you solution as below:
Assignment2inputfile.txt File:
The quick brown fox jumped over the lazy dog
count_vowels.php File:
<?php
#openfile
$file = "Assignment2inputfile.txt" ;
$document = fopen($file,'r');
$text = fread($document,filesize("Assignment2inputfile.txt"));
fclose($document);
?>
<html>
<br><br>
</html>
<?php
#vowelcount
$vowels = array("a", "e", "i", "o", "u");
$length = strlen($text);
$count = 0;
for ($i =0; $i < $length; $i++)
{
if (array_search($text[$i], $vowels))
{
$count++;
}
}
echo 'There are (' . $count . ') vowels in : ' . $text .'.';
?>
//Output:
//There are (11) vowels in : The quick brown fox jumped over the lazy dog.
There can be lots of solution to count vowels from text file but i am only showing how to do it rightly, please comment if anywhere i am wrong, thanks.

Carriage return PHP multi line

I'd like to do a multi line carriage return with php for the command line.
Is this possible?
I know already how to achieve it with one line print("\r") but it like to know how to do this on multiple lines.
The printed data should look like this:
$output = "
Total time passed: 34, \n
Total tests: 14/523
";
print($output . "\r");
It works for a single line so that there is not a new line added every time it is printed in the loop.
When i use it with a PHP_EOL, or \n i'm getting new lines all the time. I just want two lines to show up while updating it.
You can do this using ANSI escape
char [F
As example:
for ($i = 1; $i < 5; $i++) {
$prevLineChar = "\e[F";
sleep(1);
echo "$i\nof 5\n" . $prevLineChar . $prevLineChar;
}
You are looking for PHP_EOL, one for each carriage return. See here: https://stackoverflow.com/a/128564/2429318 for a nice friendly description.
It is one of the Core Predefined Constants in PHP
PHP_EOL (string)
The correct 'End Of Line' symbol for this platform. Available since PHP 5.0.2
You could write something like:
print("\n\n\n\n\n");
but what if you want to print a dynamic number of new lines :)
try this function:
function new_lines($n) {
for($i = 0; $i < $n; $i++) { echo PHP_EOL; }
}
call it like so :
//print 100 new lines
new_lines(100);

php regex matching issue

I have this kind of output:
1342&-4&-6
And it could be more times or less:
1342&-4 (I need to replace it with: 1342,1344)
1340&-1&-3&-5&-7 (I need to replace it with: 1340,1341,1343,1345,1347)
I've tried to use preg_match but with no success,
Can someone help me with that?
Thanks,
<?php
//so if you had sting input of "1342&-4" you would get 2 stings returned "1342" and "1344"?
//1340&-1&-3&-5&-7 --> 1340 and 1341 and 1343 and 1345 and 1347
//$str="1342&-4";
$str="1340&-1&-3&-5&-7";
$x=explode('&-',$str);
//print_r($x);
foreach ($x as $k=> $v){
if($k==0){
//echo raw
echo $v."<br>";
}else{
//remove last number add new last number
echo substr($x[0], 0, -1).$v."<br>";
}
}
output:
13401341134313451347
i used <br> you can use what ever you need or add to a new variable(array)
$array = explode('&-', $string);
$len = count($array);
for($i=1; $i<$len; $i++)
$array[$i] += $array[0] / 10 * 10;
var_dump(implode(' ', $array));

PHP: Extract word from string and get word count

I have tried for hours to figure this out, to no avail. I have searched and searched, with a lot of results saying to use an array. I can not use an array as this has not been covered in my class yet. Here is what I am to do:
I am to use a for loop to examine the characters using index variable.
When a blank character is found, this indicated the end of the word.
I then need to extract the word from the string and increment the word count, thus printing the word count and extracted word, continuing til the end of the sentence.
Then printing the total word count.
What I am stuck on is extracting the word. Here is what I have so far, which could very well be wrong but I am at my wits end here, so any little bit of push in the right direction would be great.
(Remember, I can not use arrays.)
$stringSentence = "The quick brown fox jumps over the lazy dog";
$wordcount = 1;
$blankCharacter = stripos($stringSentence, " ");
for ($i =0; $i<strlen($stringSentence);$i++)
{
$i. " ". $stringSentence{$i}."<br>";
}
if ($blankCharacter)
{
echo $wordcount++, " ";
echo substr($stringSentence,0,$blankCharacter);
}
Thanks for any help.
Have you considered just going through each individual letter to check for spaces and storing in a temporary buffer otherwise? One example:
$stringSentence = "The quick brown fox jumps over the lazy dog";
$buffer = '';
$count = 1;
$length = strlen($stringSentence);
for ($i = 0; $i < $length; $i++) {
if ($stringSentence{$i} !== ' ') {
$buffer .= $stringSentence{$i};
} else {
echo $count++ . ' ' . $buffer . ' ';
$buffer = '';
}
}
echo $count . ' ' . $buffer;
I'm not putting much explanation into my answer.. sort of a backwards approach of giving you the answer but it's up to you to understand how and why the above approach works.
Since this is home work I can't do it for you but you have an end bracket for one in the wrong place
Have a look at this sudo code and you should be in the right direction.
$blankCharacter = ' ';
for ($i =0; $i<strlen($stringSentence);$i++)
{
if (thisCharacter == $blankCharacter)
{
$wordcount++;
}
}
Arrays aren't that complicated! And a solution is very easy with it:
(Here I just explode() your string into an array. Then I simply loop through the array and print the output)
<?php
$stringSentence = "The quick brown fox jumps over the lazy dog";
$words = explode(" ", $stringSentence);
foreach($words as $k => $v)
echo "WordCount: " . ($k+1) . "| Word: $v<br>";
echo "Total WordCount: " . count($words);
?>
output:
WordCount: 1| Word: The
//...
WordCount: 9| Word: dog
Total WordCount: 9
If you want to read more about arrays see the manual: http://php.net/manual/en/language.types.array.php
EDIT:
If you can't use arrays, just use this:
Here I just loop through all characters of the sentence to check if it is either a space OR the end of the string. If the condition is true I print the word count + the substr from the last space until the current one. Then I also increment the word count with 1. At the end I simply print the total word count (note that I subtracted 1, because the last word will also add 1 to the count which is too much).
<?php
$stringSentence = "The quick brown fox jumps over the lazy dog";
$wordcount = 1;
$blankCharacter = 0;
for ($i = 0; $i < strlen($stringSentence); $i++) {
if($stringSentence[$i] == " " || $i+1 == strlen($stringSentence)) {
echo "WordCount: $wordcount | Word: " . substr($stringSentence, $blankCharacter, $i-$blankCharacter+1) . "<br>";
$blankCharacter = $i;
$wordcount++;
}
}
echo "Total WordCount: " . ($wordcount-1);
?>

Incrementing numbers with double digits in php [duplicate]

This question already has answers here:
Formatting a number with leading zeros in PHP [duplicate]
(11 answers)
Closed 7 years ago.
I would like to Increment numbers with double digits if the number is less then 10
This is what i tried so far
$i = 1;
echo $i++;
results is 1,2,3,4,5,6 so on
Then i try adding a condition
$i = 1;
if ($i++<10){
echo "0".$i++;
}else{
echo $i++;
}
Work but skipping the numbers 2,4,6,8 so on.
Can anyone tell me the proper way to do this?
If the condition is only there for the leading zero you can do this much easier with this:
<?php
$i = 10;
printf("%02d", $i++);
?>
if you want prepend something to a string use:
echo str_pad($input, 2, "0", STR_PAD_LEFT); //see detailed information http://php.net/manual/en/function.str-pad.php
On the second fragment of code you are incrementing $i twice, that's why you get only even numbers.
Incrementing a number is one thing, rendering it using a specific format is another thing. Don't mix them.
Keep it simple:
// Increment $i
$i ++;
// Format it for display
if ($i < 10) {
$text = '0'.$i; // Prepend values smaller than 10 with a zero
} else {
$text = $i;
}
// Display it
echo($text);
<?php
$i = 1;
for($i=1;$i<15;){
if($i<10){
echo '0'.$i++."<br>";
}else{
echo $i++."<br>";
}
}
?>

Categories