Highlight keywords in a paragraph

前端 未结 7 1592
梦如初夏
梦如初夏 2020-11-29 13:40

I need to highlight a keyword in a paragraph, as google does in its search results. Let\'s assume that I have a MySQL db with blog posts. When a user searches for a certain

7条回答
  •  暖寄归人
    2020-11-29 14:20

    Maybe you could do something like this when you're connected to the database:

    $keyword = $_REQUEST["keyword"]; //fetch the keyword from the request
    $result = mysql_query("SELECT * FROM `posts` WHERE `content` LIKE '%".
            mysql_real_escape_string($keyword)."%'"); //ask the database for the posttexts
    while ($row = mysql_fetch_array($result)) {//do the following for each result:
      $text = $row["content"];//we're only interested in the content at the moment
      $text=substr ($text, strrpos($text, $keyword)-150, 300); //cut out
      $text=str_replace($keyword, ''.$keyword.'', $text); //highlight
      echo htmlentities($text); //print it
      echo "
    ";//draw a line under it }

提交回复
热议问题