OK here is what i want to do
I have an array that contains keywords
$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
and i have another array that contains my whole titles
let's say
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.','Cristiano Ronaldo is World Soccer's Player of the Year 2013.','Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona','','');
so now what i want to do
is to loop my keywords array in each of the titles array element
and if there is 3 keywords in one element then do something
for example
$titiles[0] // this one has these words => Madrid , cup club
so this one is have at least 3 words of my keywords
so if each element has 3 keywords or more , then echo that array element.
any idea on how to get this working?
foreach ($titles as $t){
$te=explode(' ',$t);
$c=count(array_intersect($te,$keywords));
if($c >=3){
echo $t.' has 3 or more matches';
}
}
live demo: http://codepad.viper-7.com/7kUUEK
2 matches is your current max
if you want Madrid to match madrid
$keywords=array_map('strtolower', $keywords);
foreach ($titles as $t){
$te=explode(' ',$t);
$comp=array_map('strtolower', $te);
$c=count(array_intersect($comp,$keywords));
if($c >=3){
echo $t.' has 3 or more matches';
}
}
http://codepad.viper-7.com/itdegA
Alternatively, you could also use substr_count() to get the number of occurances. Consider this example:
$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.',"Cristiano Ronaldo is World Soccer's Player of the Year 2013.","Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona",'','');
$count = 0;
$data = array();
foreach($titles as $key => $value) {
$value = strtolower($value);
$keys = array_map('strtolower', $keywords);
foreach($keys as $needle) {
$count+= substr_count($value, $needle);
}
echo "In title[$key], the number of occurences using keywords = " .$count . '<br/>';
$count = 0;
}
Sample Output:
In title[0], the number of occurences using keywords = 3
In title[1], the number of occurences using keywords = 2
In title[2], the number of occurences using keywords = 2
In title[3], the number of occurences using keywords = 0
In title[4], the number of occurences using keywords = 0
Fiddle
Simpler with array_intersect:
$keywords = array('sport','messi','ronaldo','Barcelona','madrid','club','final','cup','player');
$titles = array('Real Madrid is the only club to have kept a European cup by winning it five times in a row.','Cristiano Ronaldo is World Soccer\'s Player of the Year 2013.','Lionel Messi Reaches $50 Million-A-Year Deal With Barcelona');
foreach($titles as $title) {
if (count(array_intersect(explode(' ',strtolower($title)), $keywords)) >= 3) {
//stuff
}
}
Related
I'm trying to make this works. I want to replace some parts of a sentence between given positions and then show the full sentence with the changes. With the following code, I'm able to make the changes but I don't know how to put together the rest of the sentence.
I have two arrays, one with the positions where a woman name appears and another one with men names. The code replaces the pronoun "his" by "her" when a woman is before a man between the intervals. The last thing I need is to reconstruct the sentence with the changes made but I don't know how to extract the rest of the sentence (the result, in the example, is from positions 0 to 20 (Maria her dress but) and 36 to 51 (Lorena her dog) but I need to extract from 20 to 36 (Peter his jeans) and 51 to the end (Juan his car) to merge them in their positions).
The result should be: "Maria her dress but Peter his jeans Lorena her dog Juan his car". I'll appreciate any help with this, I've been looking for other similar questions but I found nothing.
<?php
$womenpos = array("0","36"); //these arrays are just examples of positions
$menpos = array("20","51"); //they will change depending on the sentence
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
foreach ($womenpos as $index => $value) {
$value2 = $menpos[$index];
if($value < $value2) {
echo "\nWoman(" . $value . ") is before man(" . $value2 . ")\n";
$end = ($value2 - $value);
$improved = str_replace(' his ', ' her ',
substr($sentence, $value, $end));
echo $improved."\n";
} else {
$improved = "Nothing changed";
echo $improved;
}
}
Ok, how about this:
$womenpos = array("0","36");
$menpos = array("20","51");
$bothpos = array_merge($womenpos,$menpos);
sort ($bothpos);
print_r($bothpos);
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
for ($i = 0; $i<sizeof($bothpos); $i++) {
$start = $bothpos[$i];
if ($i ==sizeof($bothpos)-1) {
$end = strlen($sentence);
}
else {
$end = $bothpos[$i+1];
}
$length = $end-$start;
$segment = substr($sentence, $start, $length);
if (in_array($start, $womenpos)) {
$new_segment = str_replace (' his ', ' her ', $segment);
}
else { $new_segment = $segment; }
$improved .= $new_segment;
print "<li>$start-$end: $segment : $new_segment </li>\n";
}
print "<p>Improved: $improved</p>";
This combines the men's and women's position arrays to consider each stretch of text as one that might have an error. If that stretch of text starts at one of the womenpos points, then it changes 'his' to 'her'. If not it leaves it alone.
Does this get you in the direction you want to go in? I hope so!
This approaches the problem differently, but I wonder if it would provide the solution you're looking for:
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
$women = array ("Maria", "Lorena");
$words = explode (" ", $sentence);
for ($i=0; $i< sizeof($words); $i++) {
if ($words[$i] == "his" && in_array($words[$i-1], $women)) {
$words[$i] = "her";
}
}
print (join(" ", $words));
This goes through the words one at a time; if the preceding word is in the $women array and the current word is "his", it changes the word to "her". Then it spits out all the words in order.
Does this do what you need, or do you really want a complex string positioning answer?
I have tb words in a database :
=====================
= id = kata = posisi
=====================
= 1 = you = 1 =
= 2 = should= 2 =
= 3 = eat = 3 9 20 =
etc
Column posisi shows the positions of words in a sentence, that can be has 2 or more position for every word that I separated their position with space in its coloumn. The table comes from indexing process for sentence :
You should eat two bananas before lunch and eat two before your dinner and then consume one banana. i eat banana
I wanna get 5 words before and 5 next words from a keyword.
for example I submit keyword and I will get result :
eat two bananas before lunch and eat two before your dinner
and
eat two before your dinner and then consume one banana. i
here's the code I've tried :
require_once 'connection.php';
function getPosition ($keyword) {
$key = strtolower($keyword);
$query = mysql_query("SELECT * FROM words WHERE kata = '$key' ") or die(mysql_error());
while ($row = mysql_fetch_array($query)) {
$position = $row['posisi'];
}
return $position;
}
$key= 'And';
$and = getPosition($key);
$explode = explode (' ', $and);
foreach ($explode as $data => $datas){
for ($i = 1 ; $i < 6 ;$i++){
$nextdata[$i] = (int)$datas + $i;
$databefore[$i] = (int)$datas - $i;
$queryNext = mysql_query("SELECT kata FROM words WHERE posisi = '$nextdata[$i]' and posisi =$databefore[$i] ") or die(mysql_error());
while ($row = mysql_fetch_array($queryNext)) {
$position = $row['kata'];
}
//print_r($position);
}
}
But it doesn't work, maybe the problem is when it meet the column with has many position, it can't be read it. Please help me. Thank You :)
i have got a mysql database with words. I am printing all the words with a while statement. So i get like:
potato
tomato
lettace
This is all working fine, but i want to sort the words by length. I have tried:
if(strlen($go['words']) == 4 ){ echo "this are the 4 letter words:"; }
but this will print the sentence before every 4 letter word. Whereas, I want it to be printed only 1 time as a header for all 4 letter words. Of course i want to do this also for 5,6,7 letter words.
I have thought about making multiple sql query's but thats too much for the server to handle with a lot of visitors.
you can use a temporary variable like this:
$tempLen = 0;
while(...)
{
if(strlen($go['words']) == 1 && $tempLen < 1){
echo "this are the 1 letter words:";
$tempLen = 1;
}
...
if(strlen($go['words']) == 4 && $tempLen < 4){
echo "this are the 4 letter words:";
$tempLen = 4;
}
...
}
Is this what you want?
$words = array("fish", "mouse", "rabbit", "turtle", "duck");
sort($words);
$last_letter_count = 0;
foreach($words as $word)
{
if ( strlen($word) != $last_letter_count )
{
$last_letter_count = strlen($word);
echo "These are the $last_letter_count letter words:\n";
}
echo $word . "\n";
}
output:
These are the 4 letter words:
duck
fish
These are the 5 letter words:
mouse
These are the 6 letter words:
rabbit
turtle
I ran an election that has a variable number of winners for each category. (One category can have 3 winners, another 1 winner, another 2 winners, etc.)
Currently I am displaying the results like this:
foreach($newarray as $key => $value){
echo $key . $value . “<br>”;
}
This returns
Barack Obama 100
Mitt Romney 100
John Smith 94
Jane Smith 85
What I need to do is have it echo out something if two of the values are the same based on that predetermined number. So, if the predetermined number was one, it would show this:
Barack Obama 100 tie
Mitt Romney 100 tie
John Smith 94
Jane Smith 85
If the predetermined number was two, it would show this since the second and third values aren’t the same:
Barack Obama 100 winner
Mitt Romney 100 winner
John Smith 94
Jane Smith 85
Thank you for your time.
$max = max($array);
$tie = count(array_keys($array,$max)) > $predeterminedNumber;
foreach($newarray as $key => $value){
echo $key . $value . ($value==$max ? ($tie ? ' tie' :' winner') : ''). '<br>';
}
Allthough it becomes a bit more complex if you need the 3 winners don't necessarily have the same score:
$predefinedNumber = whatever;
arsort($array);
//first $predefinedNumber are either winners or tied.
$winners = array_slice($array,0,$predefinedNumber,true);
//the next entry determines whether we have ties
$next = array_slice($array,$predefinedNumber,1,true);
//active tie on entries with this value
$nextvalue = reset($next);
//the above 2 statements would be equivalent to (take your pick):
//$values = array_values($array);
//$nextvalue = $values[$predefinedNumber];
foreach($array as $key => $value){
echo $key.' '.$value;
if($value == $nextvalue){
echo ' tie';
} else if(isset($winners[$key])){
echo ' winner';
}
echo '<br>';
}
I want to replace one random word of which are several in a string.
So let's say the string is
$str = 'I like blue, blue is my favorite colour because blue is very nice and blue is pretty';
And let's say I want to replace the word blue with red but only 2 times at random positions.
So after a function is done the output could be like
I like red, blue is my favorite colour because red is very nice and blue is pretty
Another one could be
I like blue, red is my favorite colour because blue is very nice and red is pretty
So I want to replace the same word multiple times but every time on different positions.
I thought of using preg_match but that doesn't have an option that the position of the words peing replaced is random also.
Does anybody have a clue how to achieve this?
Much as I am loathed to use regex for something which is on the face of it very simple, in order to guarantee exactly n replaces I think it can help here, as it allows use to easily use array_rand(), which does exactly what you want - pick n random items from a list of indeterminate length (IMPROVED).
<?php
function replace_n_occurences ($str, $search, $replace, $n) {
// Get all occurences of $search and their offsets within the string
$count = preg_match_all('/\b'.preg_quote($search, '/').'\b/', $str, $matches, PREG_OFFSET_CAPTURE);
// Get string length information so we can account for replacement strings that are of a different length to the search string
$searchLen = strlen($search);
$diff = strlen($replace) - $searchLen;
$offset = 0;
// Loop $n random matches and replace them, if $n < 1 || $n > $count, replace all matches
$toReplace = ($n < 1 || $n > $count) ? array_keys($matches[0]) : (array) array_rand($matches[0], $n);
foreach ($toReplace as $match) {
$str = substr($str, 0, $matches[0][$match][1] + $offset).$replace.substr($str, $matches[0][$match][1] + $searchLen + $offset);
$offset += $diff;
}
return $str;
}
$str = 'I like blue, blue is my favorite colour because blue is very nice and blue is pretty';
$search = 'blue';
$replace = 'red';
$replaceCount = 2;
echo replace_n_occurences($str, $search, $replace, $replaceCount);
See it working
echo preg_replace_callback('/blue/', function($match) { return rand(0,100) > 50 ? $match[0] : 'red'; }, $str);
Well, you could use this algorithm:
calculate the random amount of times you want to replace the string
explode the string into an array
for that array replace the string occurence only if a random value between 1 and 100 is % 3 (for istance)
Decrease the number calculated at point 1.
Repeat until the number reaches 0.
<?php
$amount_to_replace = 2;
$word_to_replace = 'blue';
$new_word = 'red';
$str = 'I like blue, blue is my favorite colour because blue is very nice and blue is pretty';
$words = explode(' ', $str); //convert string to array of words
$blue_keys = array_keys($words, $word_to_replace); //get index of all $word_to_replace
if(count($blue_keys) <= $amount_to_replace) { //if there are less to replace, we don't need to randomly choose. just replace them all
$keys_to_replace = array_keys($blue_keys);
}
else {
$keys_to_replace = array();
while(count($keys_to_replace) < $amount_to_replace) { //while we have more to choose
$replacement_key = rand(0, count($blue_keys) -1);
if(in_array($replacement_key, $keys_to_replace)) continue; //we have already chosen to replace this word, don't add it again
else {
$keys_to_replace[] = $replacement_key;
}
}
}
foreach($keys_to_replace as $replacement_key) {
$words[$blue_keys[$replacement_key]] = $new_word;
}
$new_str = implode(' ', $words); //convert array of words back into string
echo $new_str."\n";
?>
N.B. I just realized this will not replace the first blue, since it is entered into the word array as "blue," and so doesn't match in the array_keys call.