Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
Is there any PHP function that will return which string (banana, apple, grapes) has the most number of occurrence within a given string? In this example it should return apple though orange has the one with the most number.
See code + explanation.
<?php
$interesting = array('banana', 'apple', 'grapes');
$string = "apple grapes apple banana otherwords more words apple grapes apple orange";
// Explode into array
$array = explode(" ", $string);
// Group the values
$count = array_count_values($array);
// Sort the grouping by highest occurence to lowest
arsort($count);
// Get the keys of the most occurring
$keys = array_keys($count);
// compare key against the $interesting array for what you're interested in
$most_occurring = '';
foreach ($keys as $i) {
if (in_array($i, $interesting, true)) {
$most_occurring = $i;
break;
}
}
// Print output
echo "Most occurring $most_occurring, $count[$most_occurring] occurences.";
?>
Although the answer by rurouni88 is very nice but it no longer caters for the added requirement, which is that not all words are important and you are specifying which words to look for. You can do
<?php
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
$words=array("banana", "apple", "grapes");
foreach($words as $word)
{
$counts[$word]=substr_count($string,$word);
}
arsort($counts);
reset($counts);
if($counts[0]>0)
echo key($counts); // apple
else
echo "Your words are not present";
?>
Fiddle
You can try this:
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
$array = explode(" ", $string);
$words = array_unique($array);
$counter = 0;
$returnWord = null;
foreach($words as $word){
$currentWordCount = substr_count($string, $word);
if($currentWordCount > $counter){
$counter = $currentWordCount;
$returnWord = $word;
}
}
echo "Most occurrences: ".$returnWord ." : ".$counter;
Most occurrences: orange : 7
EDIT:
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
$words = array("banana", "apple", "grapes");
$counter = 0;
$returnWord = null;
foreach($words as $word){
$currentWordCount = substr_count($string, $word);
if($currentWordCount > $counter){
$counter = $currentWordCount;
$returnWord = $word;
}
}
echo "Most occurrences: ".$returnWord ." : ".$counter;
Most occurrences: apple : 4
yes, it's called substr_count!
it accepts the string, the name of the occurrence and the substring to analyze.
for example, if you want to check the max number of occurrences in that string, you could build an array with all the names you want to check and then for every value call this function.
example source code:
// initialize your string
$string = "apple grapes apple banana otherwords more words apple grapes apple orange";
// make an array with all the string names
$occurrences = explode(" ", $string);
// remove duplicate entries from the array
$occurrences = array_unique($occurrences);
// for every name, in an associative position, count the number of that occurrence in our string
foreach ($occurrences as $occurrence) {
$count[$occurrence] = substr_count($string, $occurrence);
}
// let see what it contains
var_dump($count);
// print out where it finds the max number of occorrences
echo "max occurrence found here: " . array_search(max($count), $count);
The rurouni88's solution is good and elegant, but it has a little overhead due to sorting. For large data probably the best way is to write ad-hoc function in O(nm):
function max_occurrences($array, $valid) {
$count = array();
$maxValue = 0;
$maxEl = "";
foreach( $array as $v ){
if ( ! in_array($v, $valid, true) )
continue;
isset ( $count[$v] ) ? $count[$v]++ : $count[$v]=1 ;
if ( $count[$v] > $maxValue ) {
$maxValue = $count[$v];
$maxEl = $v;
}
}
return $maxEl;
}
$string = "apple grapes apple banana otherwords more words apple grapes apple orange orange orange orange orange orange orange";
echo max_occurrences(explode(" ",$string), array("apple","grapes", "banana"));
Related
I try to get the result
danny love to eat orange and banana and grapes
Is it possible to get it through the function foreach
my Sample Code
$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ';
//NOT THIS METHOD
// echo $var [0];
// echo ("and");
// echo $var [1];
// echo ("and");
// echo $var [2];
//Through this method
foreach ($var as $fruit) {
echo $fruit ;
echo ("and");
}
The result I get if i use foreach
danny love to eat orange and banana and grapes and
What's wrong ? :(
You're echoing 'and' one too many times. You don't want to echo 'and' if you're on the last element.
Try this instead.
$var = array (" orange "," banana "," grapes ");
echo 'danny love to eat ' .implode('and',$var);
#bassxzero's answer is a great (In fact, I would recommend doing it that way over this way), but I wanted to show another way you could do this if you wanted to use a foreach loop still if you wanted to.
$var = array ("orange","banana","grapes");
$string = 'danny love to eat ';
//Through this method
foreach ($var as $fruit) {
$string .= $fruit. " and ";
}
$string = substr($string, 0, -5);
echo $string;
In my code, we are building a string that contains all the words that you want seperated by " and ". Then as soon as the loop is done, we use substr() to remove the very last " and " so that $string equals the string you were expecting.
Another solution could be
$var = array (" orange "," banana "," grapes ");
$str = 'danny love to eat ';
$total = count($var); // counts your aray
foreach ($var as $fruit) {
$total--; // decrements $total value
$str .= $total < 1 ? $fruit : $fruit.' and '; //if $total is reduced to 0 your loop is on the last repeat, so dont print 'and' anymore
}
echo $str;
Anyway implode way is the most elegant here.
I want to search for two or more words, but not able to match the exact word.
If I use some other function like stripos() I don't get the required output.
$string = "abc india ltd";
$Arr = array('xyz ab','abc india', 'pqr', 'yz lmn');
$Arr = implode('',$Arr);
if (preg_match_all("/$string/", $Arr)) {
echo '<b>'.'found'.'<font color="green">'.$string.'</font>'.'</b>';
}
or (Both Same, But want to avoid using inside a loop)
$string = "abc india ltd";
$Arr = array('xyz ab','abc india', 'pqr', 'yz lmn');
foreach ($Arr as $value) {
if (preg_match_all("/$string/", $value)) {
echo '<b>'.'found '.'<font color="green">'.$string.'</font>'.'</b>';
}
}
I think you want like this:-
<?php
$string = "abc india";
$Arr = array('xyz india','abc india', 'pqr', 'yz lmn',"xyz abc india");
foreach($Arr as $val){
$explode_string = explode(" ",$string);
$counter =0;
foreach($explode_string as $explode_str){
if(strpos($val,$explode_str) !== FALSE){
$counter +=1;
}
}
if($counter>=2){
echo $val. " have exact ".$counter. " word matches";
echo PHP_EOL;
}
}
Output:-https://eval.in/831808
Note:- check it with all possible test-cases and let us know, worked or not?
This leverages some smart array functions to keep the code block concise and avoid manually incrementing a counter:
Code: (Demo)
$input_string="abc india ltd";
$input_array=explode(' ',$input_string);
$search_array=array('xyz ab','abc india','ltd abc','yz lmn');
foreach($search_array as $search_string){
if(sizeof(array_intersect($input_array,explode(' ',$search_string)))>1){
echo "More than one word in $search_string was found in $input_string\n";
}
}
Output:
More than one word in abc india was found in abc india ltd
More than one word in ltd abc was found in abc india ltd
*note, array_intersect() generates a new array that only contains elements that exist in both provided arrays. sizeof() is an alias of count().
I need to count some specific words in string(How many times some word occurs in a string), How can I do it in php?
Example;
$words = array("woman", "murder", "rape", "female", "dowry");
$string = "A dowry deaths is a murder or suicide of a married woman caused by a dispute over her dowry.[4] In some cases, husbands and in-laws will attempt to extort a greater dowry through continuous harassment and torture which sometimes results in the wife committing suicide";
The first item is the bundle of some word, If this word match with below string increase its value....
Example of result like be:
dowry= 1;
murder =2;
women =5;
Try:
substr_count — Count the number of substring occurrences
$string = "A dowry deaths is a murder or suicide of a married woman caused by a dispute over her dowry.[4] In some cases, husbands and in-laws will attempt to extort a greater dowry through continuous harassment and torture which sometimes results in the wife committing suicide";
$words = array("women", "murder","rape","female","dowry");
foreach($words as $word) {
echo $word." occurance are ".substr_count($string, $word)." times <br />";
}
Output:
women occurance are 0 times
murder occurance are 1 times
rape occurance are 0 times
female occurance are 0 times
dowry occurance are 3 times
function substr_count does what you want
foreach($words as $word)
echo $word .' ' . substr_count($string, $word) . "\n";
result
women 0
murder 1
rape 0
female 0
dowry 3
demo
using substr_count is going to be straightforward
$string = 'I just ate a delicious apple, and John ate instead a banana ice cream';
$words = ['banana', 'apple', 'kiwi'];
foreach($words as $word) {
$hashmap[$word] = substr_count($string, $word);
}
now $hashmap contains an associative array with word => occurrences
array(3) {
["banana"] => int(1)
["apple"] => int(1)
["kiwi"] => int(0)
}
You can Split the string into words and then loop through the array of words and check if it is one of the words inside the $words array is the same.
$arrayOfString = explode(" ", $string); //splitting in between spaces will return a new array
for ($i = 1; $i <= $arrayOfString.count(); $i++) //loop through the arrayOfString array
{
for($j = $words.count(); $j >= 1; $j--)//loop through the words array
{
if($arrayOfString[i] == $words[j])
{
echo("You have a match with: " + $words[j]); //Add your count logic here
}
}
}
Hopefully this works for you.
There are probably better ways for you to do this, but I like this logic myself.
I have some data in the following format.
Orange - $3.00
Banana - $1.25
I would like to print this as only as follows:
Orange
Banana
I tried using following code in a loop but the data may have 0 in other places as well. So if I can find 0 only at the end for a specific line.
$pos=strpos($options, "0");
$options = substr($options, 0, $pos)."\n";
Any ideas?
Is this what you're looking for?
<?php
$input = 'Orange - $3.00';
list($fruit, $price) = explode('-', $input);
?>
Or if you want to proces all the input:
<?php
$input = 'Orange - $3.00
Banana - $1.25';
$fruitlist = array();
$sepLines = explode("\n", $input);
foreach($seplines as $line)
{
list($fruit, $price) = explode(' - ', $line);
$fruitlist[] = $fruit;
}
?>
Are you trying to print only the name of the item and not the price?
$n=explode(" - ", "Banana - $1.25");
print $n[0];
$string = explode("-", $originalText);
$word = $string[0];
and thats it :)
I got an array which has 7 types of fruit:
$fruits = array(
"lemon",
"orange",
"banana",
"apple",
"cherry",
"apricot",
"Blueberry"
);
I don't know how to print out the data in a way that the outcome will like this:
<A>
Apple, Apricot <!--(Note that Apricot is followed by Apple in alphabetic order)-->
<B>
Banana
<C>
Cherry
<L>
Lemon
<O>
Orange
I am sorry that the question may be a bit difficult.
But please kindly help if you could.
I'd first use an array sorting function like sort(), and then create a loop that goes through the array and keeps track of what the first letter of the last word it output is - each time the first letter changes, output a new heading first.
Try this:
sort($fruit);
$lastLetter = null;
foreach ($fruit as $f) {
$firstLetter = substr($f, 0, 1);
if ($firstLetter != $lastLetter) {
echo "\n" . $firstLetter . "\n";
$lastLetter = $firstLetter;
}
echo $f . ", ";
}
There's some tidying up needed from that snippet, but you get the idea.
You can do this:
// make the first char of each fruit uppercase.
for($i=0;$i<count($fruits);$i++) {
$fruits[$i] = ucfirst($fruits[$i]);
}
// sort alphabetically.
sort($fruits);
// now create a hash with first letter as key and full name as value.
foreach($fruits as $fruit) {
$temp[$fruit[0]][] = $fruit;
}
// print each element in the hash.
foreach($temp as $k=>$v) {
print "<$k>\n". implode(',',$v)."\n";
}
Working example
This should do what you are looking for:
$fruits = array("lemon","orange","banana","apple","cherry","apricot","Blueberry");
//place each fruit in a new array based on its first character (UPPERCASE)
$alphaFruits = array();
foreach($fruits as $fruit) {
$firstChar = ucwords(substr($fruit,0,1));
$alphaFruits[$firstChar][] = ucwords($fruit);
}
//sort by key
ksort($alphaFruits);
//output each key followed by the fruits beginning with that letter in a order
foreach($alphaFruits as $key=>$fruits) {
sort($fruits);
echo "<{$key}>\n";
echo implode(", ", $fruits)."\n";
}