Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 突出显示段落中的关键词_Php_Search_String - Fatal编程技术网

Php 突出显示段落中的关键词

Php 突出显示段落中的关键词,php,search,string,Php,Search,String,我需要在段落中突出显示一个关键词,就像谷歌在搜索结果中所做的那样。假设我有一个带有博客帖子的MySQL数据库。当用户搜索某个关键字时,我希望返回包含这些关键字的帖子,但只显示部分帖子(包含搜索关键字的段落)并突出显示这些关键字 我的计划是: 查找内容中包含搜索关键字的帖子id 再次阅读那篇文章的内容,将每个单词放入一个固定的缓冲区数组(50个单词),直到我找到关键字 你能帮我解释一下逻辑吗,或者至少告诉我我的逻辑是否正确?我正处于PHP学习阶段 当您连接到数据库时,可能可以执行以下操作: $

我需要在段落中突出显示一个关键词,就像谷歌在搜索结果中所做的那样。假设我有一个带有博客帖子的MySQL数据库。当用户搜索某个关键字时,我希望返回包含这些关键字的帖子,但只显示部分帖子(包含搜索关键字的段落)并突出显示这些关键字

我的计划是:

  • 查找内容中包含搜索关键字的帖子id
  • 再次阅读那篇文章的内容,将每个单词放入一个固定的缓冲区数组(50个单词),直到我找到关键字

你能帮我解释一下逻辑吗,或者至少告诉我我的逻辑是否正确?我正处于PHP学习阶段

当您连接到数据库时,可能可以执行以下操作:

$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, '<strong>'.$keyword.'</strong>', $text); //highlight
  echo htmlentities($text); //print it
  echo "<hr>";//draw a line under it
}
$keyword=$\u请求[“关键字]//从请求中获取关键字
$result=mysql\u query(“从`posts`中选择*WHERE`content`类似“%””。
mysql_real_escape_字符串($keyword)。“%”//向数据库查询PostText
虽然($row=mysql\u fetch\u array($result)){//对每个结果执行以下操作:
$text=$row[“content”];//我们现在只对内容感兴趣
$text=substr($text,strrpos($text,$keyword)-150300);//剪切
$text=str_replace($keyword,。$keyword.,$text);//高亮显示
echo htmlentities($text);//打印它
echo“
”;//在它下面画一条线 }
如果你是一名初学者,这将不会像某些人认为的那样非常容易

我认为您应该执行以下步骤:

  • 根据用户搜索的内容构建查询(注意sql注入)
  • 获取结果并组织它们(一个数组就可以了)
  • 从上一个数组生成html代码
  • 在第三步中,您可以使用一些正则表达式将用户搜索的关键字替换为粗体的等效关键字。 str_替换也可以工作

    我希望这有助于。。。
    如果您可以提供您的数据库结构,也许我可以给您一些更精确的提示…

    如果您希望剪切相关段落,在执行上述str_replace函数后,您可以使用stripos()查找这些强段的位置,并使用该位置的偏移量与substr()配合使用删去段落的一部分,例如:

    $searchterms; foreach($searchterms as $search) { $paragraph = str_replace($search, "<strong>$search</strong>", $paragraph); } $pos = 0; for($i = 0; $i < 4; $i++) { $pos = stripos($paragraph, "<strong>", $pos); $section[$i] = substr($paragraph, $pos - 100, 200); } $searchterms; foreach($searchterms作为$search) { $PARATION=str_替换($search,“$search”,$PARATION); } $pos=0; 对于($i=0;$i<4;$i++) { $pos=stripos($strong>,$pos); $section[$i]=substr($section,$pos-100200); } 这将给你一个小句子数组(每个200个字符)来使用你想要的方式。搜索离切割位置最近的空间,并从那里切割以避免半个单词,这也可能是有益的。哦,您还需要检查错误,但我会让您自行决定。

    如果它包含html(请注意,这是一个非常健壮的解决方案):

    好的,那么它所做的就是返回一个匹配数组,其周围有
    $maxStubSize
    个单词(即前面的数字最多有一半,后面的数字最多有一半)

    因此,给定一个字符串:

    <p>a whole 
        <b>bunch of</b> text 
        <a>here for</a> 
        us to foo bar baz replace out from this string
        <b>bar</b>
    </p>
    
    因此,您可以通过按
    strlen
    对列表进行排序,然后选择两个最长的匹配项来构建结果简介。。。(假设php 5.3+):

    其结果是:

    <p><span class="highlight">foo</span><b>bar</b></p>
    
    here for us to foo <span class="highlight">bar</span> baz replace out...a whole <span class="highlight">bunch</span> of text here for 
    
    在这里我们要用foo-bar-baz替换掉…这里有一大堆文本
    

    我希望这有助于。。。(我确实觉得这有点…臃肿…我相信有更好的方法可以做到这一点,但这里有一种方法)…

    您可以尝试使用
    explode
    将数据库搜索结果集分解为一个数组,然后对每个搜索结果使用
    array\u search()
    。将下面示例中的
    $distance
    变量设置为希望在
    $keyword
    的第一个匹配项的两侧显示多少个单词

    在这个示例中,我将lorum ipsum文本作为示例数据库结果段落,并将
    $关键字设置为'scelerisque'。显然,您应该在代码中替换这些

    //example paragraph text
    $lorum = 'Nunc nec magna at nibh imperdiet dignissim quis eu velit. 
    vel mattis odio rutrum nec. Etiam sit amet tortor nibh, molestie 
    vestibulum tortor. Integer condimentum magna dictum purus vehicula 
    et scelerisque mauris viverra. Nullam in lorem erat. Ut dolor libero, 
    tristique et pellentesque sed, mattis eget dui. Cum sociis natoque 
    penatibus et magnis dis parturient montes, nascetur ridiculus mus. 
    .';
    
    //turn paragraph into array
    $ipsum = explode(' ',$lorum);
    //set keyword
    $keyword = 'scelerisque';
    //set excerpt distance
    $distance = 10;
    
    //look for keyword in paragraph array, return array key of first match
    $match_key = array_search($keyword,$ipsum);
    
    if(!empty($match_key)){
    
        foreach($ipsum as $key=>$value){
            //if paragraph array key inside excerpt distance
            if($key > $match_key-$distance and $key< $match_key+$distance){ 
                //if array key matches keyword key, bold the word
                if($key == $match_key){
                    $word = '<b>'.$value.'</b>';
                    }
                else{
                    $word = $value;
                    }
                //create excerpt array to hold words within distance
                $excerpt[] = $word;
                }
    
            }
        //turn excerpt array into a string
        $excerpt = implode(' ',$excerpt);
        }
    //print the string
    echo $excerpt;
    
    //示例段落文本
    $lorum='在nibh帝国的大教堂里,显贵们向欧盟致敬。
    韦尔马蒂斯·奥迪奥·鲁特鲁姆nec。这是我的错,莫莱斯蒂
    前庭斜颈。整粒调味品
    还有权杖毛里斯·维韦拉。在洛雷姆埃拉特。多洛自由女神,
    tristique和pellentesque,mattis eget dui。自然社会
    对虾和马格尼对虾产褥期的蒙特斯,印度对虾。
    .';
    //将段落转换为数组
    $ipsum=爆炸(“”,$lorum);
    //设置关键字
    $keyword='scelerisque';
    //设置摘录距离
    $distance=10;
    //在段落数组中查找关键字,返回第一个匹配的数组键
    $match\u key=数组搜索($keyword,$ipsum);
    如果(!空($match_key)){
    foreach($ipsum as$key=>$value){
    //如果段落数组键位于摘录距离内
    如果($key>$match_key-$distance和$key<$match_key+$distance){
    //如果数组键与关键字键匹配,请将单词加粗
    如果($key==$match\u key){
    $word='.$value'.';
    }
    否则{
    $word=$value;
    }
    //创建摘录数组以在一定距离内保存单词
    $extract[]=$word;
    }
    }
    //将摘录数组转换为字符串
    $EXECRPT=内爆(“”,$EXECRPT);
    }
    //打印字符串
    echo$摘录;
    
    $extract
    返回:
    “tortor的前庭。完整的调味品大词典purus Vehicleu et scelerisque mauris viverra。lorem erat.Ut dolor libero中的Nullam,”

    以下是纯文本的解决方案:

    $str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
    $keywords = array('co');
    $wordspan = 5;
    $keywordsPattern = implode('|', array_map(function($val) { return preg_quote($val, '/'); }, $keywords));
    $matches = preg_split("/($keywordsPattern)/ui", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
    for ($i = 0, $n = count($matches); $i < $n; ++$i) {
        if ($i % 2 == 0) {
            $words = preg_split('/(\s+)/u', $matches[$i], -1, PREG_SPLIT_DELIM_CAPTURE);
            if (count($words) > ($wordspan+1)*2) {
                $matches[$i] = '…';
                if ($i > 0) {
                    $matches[$i] = implode('', array_slice($words, 0, ($wordspan+1)*2)) . $matches[$i];
                }
                if ($i < $n-1) {
                    $matches[$i] .= implode('', array_slice($words, -($wordspan+1)*2));
                }
            }
        } else {
            $matches[$i] = '<b>'.$matches[$i].'</b>';
        }
    }
    echo implode('', $matches);
    
  • 如果要匹配子单词但突出显示整个单词,请在关键字前后使用可选单词字符
    \w

    "/(\w*?(?:$keywordsPattern)\w*)/ui"
    

  • 我在搜索如何突出显示关键字搜索结果时发现了这篇文章。我的要求是:

    • 一定是整句话
    • array(4) { [0]=> string(75) "here for us to foo <span class="highlight">bar</span> baz replace out from " [3]=> string(34) "<span class="highlight">bar</span>" [4]=> string(62) "a whole <span class="highlight">bunch</span> of text here for " [7]=> string(39) "<span class="highlight">bunch</span> of" }
    usort($results, function($str1, $str2) { 
        return strlen($str2) - strlen($str1);
    });
    $description = implode('...', array_slice($results, 0, 2));
    
    here for us to foo <span class="highlight">bar</span> baz replace out...a whole <span class="highlight">bunch</span> of text here for 
    
    //example paragraph text
    $lorum = 'Nunc nec magna at nibh imperdiet dignissim quis eu velit. 
    vel mattis odio rutrum nec. Etiam sit amet tortor nibh, molestie 
    vestibulum tortor. Integer condimentum magna dictum purus vehicula 
    et scelerisque mauris viverra. Nullam in lorem erat. Ut dolor libero, 
    tristique et pellentesque sed, mattis eget dui. Cum sociis natoque 
    penatibus et magnis dis parturient montes, nascetur ridiculus mus. 
    .';
    
    //turn paragraph into array
    $ipsum = explode(' ',$lorum);
    //set keyword
    $keyword = 'scelerisque';
    //set excerpt distance
    $distance = 10;
    
    //look for keyword in paragraph array, return array key of first match
    $match_key = array_search($keyword,$ipsum);
    
    if(!empty($match_key)){
    
        foreach($ipsum as $key=>$value){
            //if paragraph array key inside excerpt distance
            if($key > $match_key-$distance and $key< $match_key+$distance){ 
                //if array key matches keyword key, bold the word
                if($key == $match_key){
                    $word = '<b>'.$value.'</b>';
                    }
                else{
                    $word = $value;
                    }
                //create excerpt array to hold words within distance
                $excerpt[] = $word;
                }
    
            }
        //turn excerpt array into a string
        $excerpt = implode(' ',$excerpt);
        }
    //print the string
    echo $excerpt;
    
    $str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
    $keywords = array('co');
    $wordspan = 5;
    $keywordsPattern = implode('|', array_map(function($val) { return preg_quote($val, '/'); }, $keywords));
    $matches = preg_split("/($keywordsPattern)/ui", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
    for ($i = 0, $n = count($matches); $i < $n; ++$i) {
        if ($i % 2 == 0) {
            $words = preg_split('/(\s+)/u', $matches[$i], -1, PREG_SPLIT_DELIM_CAPTURE);
            if (count($words) > ($wordspan+1)*2) {
                $matches[$i] = '…';
                if ($i > 0) {
                    $matches[$i] = implode('', array_slice($words, 0, ($wordspan+1)*2)) . $matches[$i];
                }
                if ($i < $n-1) {
                    $matches[$i] .= implode('', array_slice($words, -($wordspan+1)*2));
                }
            }
        } else {
            $matches[$i] = '<b>'.$matches[$i].'</b>';
        }
    }
    echo implode('', $matches);
    
    "/\b($keywordsPattern)\b/ui"
    
    "/(\w*?(?:$keywordsPattern)\w*)/ui"
    
    $keywords = array("fox","jump","quick");
    $string = "The quick brown fox jumps over the lazy dog";
    $test = "The quick brown fox jumps over the lazy dog"; // used to compare values at the end.
    
    if(isset($keywords)) // For keyword search this will highlight all keywords in the results.
        {
        foreach($keywords as $word)
            {
            $pattern = "/\b".$word."\b/i";
            $string = preg_replace($pattern,"<span class=\"highlight\">".$word."</span>", $string);
            }
        }
     // We must compare the original string to the string altered in the loop to avoid having a string printed with no matches.
    if($string === $test)
        {
        echo "No match";
        }
    else
        {
        echo $string;
        }
    
    The <span class="highlight">quick</span> brown <span class="highlight">fox</span> jumps over the lazy dog.