Search code examples
phpwords

php outputting text with keywords highlighted


i have a system that outputs a film review, when it is outputted i want the keywords that appear in it from 2 tables - negative and positive to be in a different colour any idea to do this ? The code is below

<?php

// Connect to database
mysql_connect("sdd", "sdsd", "") or die(mysql_error());
mysql_select_db("sdsd") or die(mysql_error());

$id = mysql_real_escape_string($_POST['reviewid']); 

//$query = "select * from review where id = '$id'";
$query = mysql_fetch_assoc(mysql_query("SELECT filmreview FROM review WHERE id = '$id'"));
$pos = mysql_query("SELECT word FROM positive");
$neg = mysql_query("SELECT word FROM negative");


//Variables 
$review_text = $query['filmreview'];
$good = 0;
$bad = 0; 


// Gets words in to a text array and converts to lower case 
$cnt_r = array_count_values(array_map('mb_strtolower',str_word_count($review_text, 1)));

// Gets the positive words and check for the word in the text  
    while($check = mysql_fetch_assoc($pos)){
       $lower = mb_strtolower($check['word']);
     if(isset($cnt_r[$lower])){
    $good+= $cnt_r[$lower];
    echo $check ['word'];
    echo "<p>"; 
     } 
    }

// Gets the negative words and check for the word in the text 
while($check = mysql_fetch_assoc($neg)){
  $lower = mb_strtolower($check['word']);
 if(isset($cnt_r[$lower])){
    $bad+= $cnt_r[$lower];
        echo $check ['word'];
        echo "<p>";
 }  
} 


// If there are more positive words than negative than the review is positive  
if ($good > $bad)
{
    echo "<p>"; 
    echo "This is a positive review";
    echo "<p>";
}

// If there are more negative words than positive than the review is negative 
else if ($good < $bad)
{
    echo "<p>";
    echo "This is a negative review";
    echo "<p>";
}

// If there are the same amount of positive and negative words than the review is average 
else if ($good == $bad)
{
    echo "<p>";
    echo "This is an average review";
    echo "<p>";
}

//Prints out the number of postive and negative words found 
echo "Good words: " . $good . " and Bad words: " . $bad;
echo "<p>";
echo $query ['filmreview'];
echo "<p>";
echo "This is <font color=\"blue\">blue</font>!"; 



echo "<form method='post' action='welcome.html'>";
echo "<input type='submit' name='searchagain' value='Search'>";
?>

Solution

  • Just search and find your keywords in the text and then just replace them. So roughly

        if($postivekeyword) {  
           $newpostivekeyword = '<span class="positive">'.$postivekeyword.'</span>';
       }
        if($negativekeyword) {  
          $newnegativekeyword = '<span class="negative">'.$negativekeyword.'</span>';
        }
    

    Then just

       $new_review_text = str_replace($postivekeyword, $newpostivekeyword, $review_text);