Counting vowels in a text file with PHP - 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.

Related

PHP Explode Show Seperator

So I wrote the following code to show the words after the fourth full stop / period in a sentence.
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$minText = explode(".", $text);
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i];
}
The algorithm is working and it is showing me the rest of the sentence after the fourth "." full stop / period.... My problem is that the output is not showing the full stops in the sentence therefore it is showing me just text without the proper punctuation "." .... Can someone please help me out on how to fix the code to display also the full stops / periods ??
Thanks a lot
you could try this...
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i].".";
}
notice the added period at the end of the echo command // .".";
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$minText = explode(".", $text);
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i].".";
}
Instead of splitting the input string and then iterating over it, you can find the nth position of the separator (.) in the string by using strpos() function by changing the offset parameter.
Then, it is just the matter of printing the sub-string from the position we just determined.
<?php
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$pos = 0;
//find the position of 4th occurrence of dot
for($i = 0; $i < $limit; $i++) {
$pos = strpos($text, '.', $pos) + 1;
}
print substr($text, $pos);
If desired output is "seperated.with.full.stops.", then you can use:
<?php
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
$minText = explode(".", $text);
$minText = array_slice($minText, $limit);
echo implode('.', $minText) . '.';
If you want to break it up on the periods between words, but keep the one at the end as actual punctuation, you may want to use preg_replace() to convert the periods to another character and then explode it.
$text = "this.is.the.message.seperated.with.full.stops.";
$limit = 4;
//replace periods if they are follwed by a alphanumeric character
$toSplit = preg_replace('/\.(?=\w)/', '#', $text);
$minText = explode("#", $toSplit);
for($i = $limit; $i < count($minText); $i++){
echo $minText[$i] . "<br/>";
}
Which Yields
seperated
with
full
stops.
Of course, if you just simply want to print all the full stops, then add them in after you echo the term.
echo $minText[$i] . ".";

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

PHP split a very big number [duplicate]

This question already has answers here:
What's HTML character code 8203?
(8 answers)
Closed 8 years ago.
I used a number below in my code:
$MyString = '06887558108616348​33464996​60139294';
When i'm trying to split MyString into a same pieces for example: 06887558, 10861634 so on... using substr or str_split that gives me:
06887558, 10861634, 8​3346, 4996​6, 0139294
Someone explain why this happend?!?
The Code what I have tried
$MyNewString; $n = 8; // How many you want before seperation
$MyNewString = substr($MyString,0,$n);
$i = $n;
while ($i < strlen($MyString)) {
$MyNewString .= '-'; // Seperator Character
$MyNewString .= substr($MyString,$i,$n);
$i = $i + $n;
}
echo $MyNewString;
add charset utf-8
add this code
echo '<meta charset="UTF-8">';
see the result I have tried
$new_string = implode(', ', str_split($n, 8));
echo $new_string;
If you're getting funny characters in the result, then they must have been in the original string. substr and str_split don't add anything.

reorder / rewrap bbcodes

I'm trying to reorder the BBCodes but I failed
so
[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶b̶]̶[̶/̶u̶]̶[̶/̶i̶]̶ ̶-̶ ̶w̶r̶o̶n̶g̶ ̶o̶r̶d̶e̶r̶ ̶ ̶
I̶ ̶w̶a̶n̶t̶ ̶i̶t̶ ̶t̶o̶ ̶b̶e̶:̶ ̶
̶[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶u̶]̶[̶/̶i̶]̶[̶/̶b̶]̶ ̶-̶ ̶r̶i̶g̶h̶t̶ ̶o̶r̶d̶e̶r̶
PIC:
I tried with
<?php
$string = '[b][i][u]foo[/b][/u][/i]';
$search = array('/\[b](.+?)\[\/b]/is', '/\[i](.+?)\[\/i]/is', '/\[u](.+?)\[\/u]/is');
$replace = array('[b]$1[/b]', '[i]$1[/i]', '[u]$1[/u]');
echo preg_replace($search, $replace, $string);
?>
OUTPUT: [b][i][u]foo[/b][/u][/i]
any suggestions ? thanks!
phew, spent awhile thinking of the logic to do this. (feel free to put it in a function)
this only works for the scenario given. Like other users have commented it's impossible. You shouldn't be doing this. Or even on server side. I'd use a client side parser just to throw a syntax error.
supports [b]a[i]b[u]foo[/b]baa[/u]too[/i]
and bbcode with custom values [url=test][i][u]foo[/url][/u][/i]
Will break with
[b] bold [/b][u] underline[/u]
And [b] bold [u][/b] underline[/u]
//input string to be reorganized
$string = '[url=test][i][u]foo[/url][/u][/i]';
echo $string . "<br />";
//search for all opentags (including ones with values
$tagsearch = "/\[([A-Za-z]+)[A-Za-z=._%?&:\/-]*\]/";
preg_match_all($tagsearch, $string, $tags);
//search for all close tags to store them for later
$closetagsearch = "/(\[\/([A-Za-z]+)\])/is";
preg_match_all($closetagsearch, $string, $closetags);
//flip the open tags for reverse parsing (index one is just letters)
$tags[1] = array_reverse($tags[1]);
//create temp var to store new ordered string
$temp = "";
//this is the last known position in the original string after a match
$last = 0;
//iterate through each char of the input string
for ($i = 0, $len = strlen($string); $i < $len; $i++) {
//if we run out of tags to replace/find stop looping
if (empty($tags[1]) || empty($closetags[1]))
continue;
//this is the part of the string that has no matches
$good = substr($string, $last, $i - $last);
//next closing tag to search for
$next = $closetags[1][0];
//how many chars ahead to compare against
$scope = substr($string, $i, strlen($next));
//if we have a match
if ($scope === "$next") {
//add to the temp variable with a modified
//version of an open tag letter to become a close tag
$temp .= $good . substr_replace("[" . $tags[1][0] . "]", "/", 1, 0);
//remove the first key/value in both arrays
array_shift($tags[1]);
array_shift($closetags[1]);
//update the last known unmatched char
$last += strlen($good . $scope);
}
}
echo $temp;
Please also note: it might be the users intention to nest the tags out of order :X

Last line and char of text file

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

Categories