Trying to spit sentence into array with words - php

I am trying to split a sentence into an array with words, one word as each element, in PHP if there is more than one word in the sentence. If there is only one word in the sentence, then I just print that one word.
My issue is when I split the sentence into words delimited by a space and put the contents into an array. I do this all using explode. But when I run through the array that explode apparently makes, it says there is nothing in the array when I try to print each item.
Here is my code:
if(isset($_GET['check'])){
$input = trim($_GET['check']);
$sentence='';
if(stripos($input, ' ')!==false){
$sentence = explode(' ', $input);
foreach($sentence as $item){
echo $item;
}
}
else{
echo $input;
}
}
Why is echo $item; printing nothing? Why isn't there anything in the array $sentence?

Your code seems to be working fine. Make sure you're getting the variable. You can do a print_r($_GET);
You can also just do this:
<?php
$_GET['check'] = 'Hey how are you?';
if (isset($_GET['check'])) {
// each word is now an element in the array
$arr = explode(' ', trim($_GET['check']));
}
// piece each word back together with a space
echo implode(' ', $arr);
?>
It doesn't matter if it's a single word or multiple words.
UPDATE: If you really want to check if the user has entered one word or more than one word you can do this:
<?php
$_GET['check'] = 'Hey how are you?';
if (str_word_count($_GET['check']) > 1) {
echo 'More than one word';
} else {
echo 'Only one word';
}
?>
Check out str_word_count

Related

PHP Find two consecutive numeric entries in array

My problem is it just replicates the number twice, though it does add the break when there is a number, but I'm trying to check if there is a number after the number, so it would say line 12 is.....
Thanks for any help
<?PHP
$lines = file_get_contents('http://www.webstitcher.com/test.txt');
$tag = str_split($lines); // puts all lines into a array
foreach ($tag as $num => $letta){
if (is_numeric($letta) == TRUE){
$num2 = $num++;
if (is_numeric($tag[$num2])){ // checks if next line is going to be another digit
$letta .= $tag[$num2];
unset($tag[$num2]); // removes line if it had another digit and adds to ouput
}
echo '<br />' . $letta;
}
else {
echo $letta;
}
}
?>
Try exploding the string using ' ' as the delimiter. This will allow you to keep the numbers whole and will ultimately help cut out a lot of the complexity.
$lines = file_get_contents('http://www.webstitcher.com/test.txt');
$tag = explode(' ', $lines); // puts all words into a array
foreach ($tag as $word){
if (is_numeric($word)) {
// if the word is numeric, simply skip to next line
// if you need to keep the number, add $word to the echo statement
echo '<br />';
}
else {
echo ' '.$word;
}
}
This way you don't have to keep track of the previous element in the array or check for the next element.
Alternatively, you could also use preg_replace which would remove the need for the loop entirely.
$lines = preg_replace('/[0-9]+/', '<br>', $words);

PHP finding out if words are contained in a large array

I need to check if an array of words ($words) is present in a larger array ($dictionary).
If all the words are there, no errors.
If one or more are not included in $dictionary, I want to send out an error message.
So far, I have come up with this:
<?php
// first I select a column from a MySQL table and retrieve
//all the words contained in that field.
$spell = "SELECT * FROM eventi WHERE utente='{$_SESSION['username']}'";
$qspell = mysql_query($spell) or die ("Error Query [".$spell."]");
while ($risu = mysql_fetch_array($qspell)){
$risu = mysql_fetch_array($qspell);
// the following lines remove parentheses, digits and multiple spaces
$desc = strtolower($risu["descrizione"]);
$words = explode(" ",$desc);
$words = str_replace("(","",$words);
$words = str_replace(")","",$words);
$words = preg_replace('/[0-9]+/','',$words);
$words = preg_replace('/\s+/',' ',$words);
// the array $dictionary is generated taking a long list
//of words from a txt file
$dictionary = file('./docs/dizionario.txt',FILE_IGNORE_NEW_LINES);
foreach($words as $k => $v){
if (in_array($v, $dictionary)){
//Do something?
} else {
$error = "error";
echo "The word ".$v." can't be found in the dictionary.";
}
}
}
if (!isset($error)){
echo "All the words are in the dictionary.";
} else {
echo "There are some unknown words. See above.";
}
?>
This code always returns one single error message, without reporting which word can't be found.
On top of that, words which are actually missing are not detected.
What am I doing wrong?
Apparently, the problem lies at the line:
$words = preg_replace('/[0-9]+/','',$words);
Removing digits somehow messes the whole matching procedure.
Without removing digits, my code works.

Check if input variables are numbers in an array

The problem is the following in PHP:
How to check if the input variables are numbers in an array if all of them was asked to separate with a " " (space) character within a form?
is_int and is_numeric don't work here, since it's a string not an array.
The answer might be easy, I'm just struggling with it in these late night hours.
The whole problem:
By using only one input field, read in numbers separated by " "(space), then print them out in ascending order. If there is any other variable besides numbers, print "error".
$str = "999 999 999 99";
$arr = explode(" ", $str);
foreach ($arr as $value) {
if(is_numeric($value)){
echo 'ok';
}
}
Might just replace the spaces:
if(is_numeric(str_replace(' ', '', $input)) {
// $input without spaces is numeric
}

PHP how to count the length of each word in the text file

i need some help. how to count the length of each word in the text file using PHP.
for example. there is the test.txt. and the contain is " hello everyone, i need some help."
how to output the text and then count the length of each word,like:
array
hello => 5
everyone => 8
i => 1
need => 4
some => 4
help => 4
i just start to learn php. so please explain the detail about the code what you write.
many thanks
This should work
$text = file_get_contents('text.txt'); // $text = 'hello everyone, i need some help.';
$words = str_word_count($text, 1);
$wordsLength = array_map(
function($word) { return mb_strlen($word, 'UTF-8'); },
$words
);
var_dump(array_combine($words, $wordsLength));
For more informations about str_word_count and its parameters see http://php.net/manual/en/function.str-word-count.php
Basically, everything is well described on php.net. The function array_map walks through given array and applies given (eg. anonymous) function on every item in that array. The function array_combine creates an array by using one array for keys and another for its values.
this is working
$stringFind="hello everyone, i need some help";
$file=file_get_contents("content.txt");/*put your file path */
$isPresent=strpos($file,$stringFind);
if($isPresent==true){
$countWord=explode(" ",$stringFind);
foreach($countWord as $val){
echo $val ." => ".strlen($val)."<br />";
}
}else{
echo "Not Found";
}
If you don't need to process the words' length later, try this:
// Get file contents
$text = file_get_contents('path/to/file.txt');
// break text to array of words
$words = str_word_count($text, 1);
// display text
echo $text, '<br><br>';
// and every word with it's length
foreach ($words as $word) {
echo $word, ' => ', mb_strlen($word), '<br>';
}
But be noticed, that str_word_count() function has many issues with UTF-8 string (f.e. Polish, Czech and similar characters). If you need those, then I suggest filtering out commas, dots and other non-word characters and using explode() to get $words array.

Word counter: Doesn't seem to give the output I need (PHP)

here's the line of code that I came up with:
function Count($text)
{
$WordCount = str_word_count($text);
$TextToArray = explode(" ", $text);
$TextToArray2 = explode(" ", $text);
for($i=0; $i<$WordCount; $i++)
{
$count = substr_count($TextToArray2[$i], $text);
}
echo "Number of {$TextToArray2[$i]} is {$count}";
}
So, what's gonna happen here is that, the user will be entering a text, sentence or paragraph. By using substr_count, I would like to know the number of occurrences of the word inside the array. Unfortunately, the output the is not what I really need. Any suggestions?
I assume that you want an array with the word frequencies.
First off, convert the string to lowercase and remove all punctuation from the text. This way you won't get entries for "But", "but", and "but," but rather just "but" with 3 or more uses.
Second, use str_word_count with a second argument of 2 as Mark Baker says to get a list of words in the text. This will probably be more efficient than my suggestion of preg_split.
Then walk the array and increment the value of the word by one.
foreach($words as $word)
$output[$word] = isset($output[$word]) ? $output[$word] + 1 : 1;
If I had understood your question correctly this should also solve your problem
function Count($text) {
$TextToArray = explode(" ", $text); // get all space separated words
foreach($TextToArray as $needle) {
$count = substr_count($text, $needle); // Get count of a word in the whole text
echo "$needle has occured $count times in the text";
}
}
$WordCounts = array_count_values(str_word_count(strtolower($text),2));
var_dump($WordCounts);

Categories