【问题标题】:search a word and highlight it using php搜索一个单词并使用 php 突出显示它
【发布时间】:2014-02-15 00:27:09
【问题描述】:

我的问题是我想在给定的字符串中找到一个单词,并且每次单击按钮时该单词的背景变化都会增加,就像在任何编辑器中进行搜索一样。

<?php 

function writeMsg()
{
$str = "my bird is funny, we fun are funny,they are     funny they are fun";
$keyword =$_GET['search'];
$strarr=explode(" ",$str);
//print_r($strarr);

    foreach ($strarr as $val) 
    {
   //print_r($val); 
   if($val==$keyword)
   {echo hi;
   $copy_date = preg_replace("/$keyword\b/",'<b     style=background-color:yellow;>'.$keyword.'</b>',   $val);
   print $copy_date;   
   }
   else
   {
   echo $val;  
   }    }
//}
?>
<html>
    <form action="#" method="get">
    Please enter word to search<input type="text"   name="search"><br/>
<input type="button" value="NEXT"   onclick="document.write('<?php 'writeMsg()';?>');" />

    </form>
</html>

【问题讨论】:

  • php 在服务器端运行——也就是说,在 html 到达之前,所有的 php 处理都已经完成。因此,您需要使用 JavaScript 之类的东西来获得一个以您想要的方式与用户交互的函数。这对您来说是一个可以接受的替代方案吗(您专门询问 php……)
  • 你有什么错误吗?
  • 更好....使用
  • 你想一键高亮所有单词吗?每次点击增加一个亮点;还是将突出显示移到下一个项目?

标签: php search word highlight using


【解决方案1】:

简单的 Javascript 实现:

String:  <input type = "text" id = "mystring">
<p>&nbsp;</p>
<div id = "mystringdiv" style="width:400px; height:120px; border:solid black 1px;"></div>

Word to search: <input type = "text" id = "searchstring"><input type = "button" value = "Search" onclick = "startSearch()">

<script type = "text/javascript">
function startSearch()
{
    var search = new RegExp(document.getElementById("searchstring").value, "g")
    var string = document.getElementById("mystring").value

    var nstring = string.replace(search, "<b style=\"background-Color:#FFFF00\">"+document.getElementById("searchstring").value+"</b>")

    document.getElementById("mystringdiv").innerHTML=nstring

}
</script>

http://jsfiddle.net/dRW84/

【讨论】:

  • 为什么这被否决了? Javascript 似乎比使用 PHP 更好,因为它不需要表单提交或 AJAX 调用来处理输入和突出显示。
  • 我认为这实际上值得投赞成票,而不是投反对票。 JS 几乎可以肯定是执行此操作的正确方法 - 尽管我不确定您的代码是否会一次突出显示所有匹配项,而不是“每次单击一次”。但问题在这一点上是模棱两可的。
  • 它适用于所有匹配项,因此正则表达式中的“g”表示“global”。测试一下:jsfiddle.net/dRW84
  • 对双重否定感到抱歉:我的意思是“我认为它会一次突出所有匹配项,而不是每次点击一次”。 “我不确定它没有”在逻辑上与“我确定它有”在逻辑上不同,但你明白了。
  • @SyntaxLAMP 如果关键字在链接中,或者恰好是页面源代码中的元素名称或其他任何内容,会发生什么?
【解决方案2】:

到目前为止,所有答案都未能解决如果在链接中使用关键字会发生什么。

这是我的解决方案。它可能并不完美,但它允许这样做。

//this code will highlight the search string in the returned search results.  It ignores text within tags

function doHighlight ($strneedle, $strhaystack){

//this fixes bug if first char is a <
if(strpos($strhaystack,"<")==0) {$strhaystack = " " . $strhaystack;}

$strhaystack = str_replace("\"","'",$strhaystack);
$newthought = "";
$i = 0;
    //only do it if we have a tag
    $findtag = strpos($strhaystack,"<");

    if ($findtag > 0){

        //count how many tags we have 
        $strCount = substr_count( $strhaystack,"<");

        //and loop that many times
        while($i < $strCount){
            $i++;
            //find opening tag
            $pos = strpos( $strhaystack,"<");
            //get text to left of opening tag
            $thoughtstart = substr($strhaystack , 0, $pos);
                //highlight that text
                $pattern = $strneedle;
                $replacement = '<span class="highlight">'.$strneedle.'</span>';
                $highlightedthought = eregi_replace($pattern, $replacement, $thoughtstart);
                //build the new string
                $newthought = $newthought . $highlightedthought;

            //find closing tag and concatenate it to new string without highlighting
            $thoughtremainder = substr($strhaystack, $pos);
                $pos = strpos( $thoughtremainder,">");
                $thoughtstart = substr($thoughtremainder , 0, $pos);
                $newthought = $newthought . $thoughtstart;      

            //make the rest of the thought the new string and loop
            $strhaystack = substr($thoughtremainder, $pos); 
        }
    }
    //if no tag, return the highlighted thought
    else{
        $pattern = $strneedle;
        $replacement = '<span class="highlight">'.$strneedle.'</span>';
        $newthought = eregi_replace($pattern, $replacement, $strhaystack);
        }

return (trim($newthought));
}

【讨论】:

    【解决方案3】:

    您可以使用像这样的 str_replace 函数来做到这一点。

    <?php
    $str = "my bird is funny, we fun are funny,they are     funny they are fun";
    $str1=$str;
    
    echo $str."<br/>";
    
    
    $find="funny"; 
    $str=str_replace($find,'<span style="color:red">'.$find.'</span>',$str);
    
    echo $str."<br/>"; //If keyword exists displays updated string
    
    $find="funky"; 
    $str=str_replace($find,'<span style="color:red">'.$find.'</span>',$str1);
    
    echo $str; //If keyword doesn't exist, Just display the same string
    ?>
    

    【讨论】:

      【解决方案4】:

      如果您不使用正则表达式,str_replace() 就可以了。它甚至还有一个内置计数器。

      <?php 
      function writeMsg(){
          $count = 0;
          $str = "my bird is funny, we fun are funny, they are funny they are fun";
          $keyword = $_GET['search'];
          $str = str_replace($keyword, "<b style='background-color:yellow;'>".$keyword."</b>",$str,$count);
          echo "There were ".$count." matches.<br />";
          echo $str;
      }
      ?>
      <html>
          <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
              Please enter word to search: <input type="text" name="search"><br/>
              <input type="submit" value="NEXT" />
          </form>
          <?php
          if(isset($_GET['search'])){
              writeMsg();
          }
          ?>
      </html>
      

      【讨论】:

      • 赞成这个,因为它实际上展示了如何调用服务器来进行 php 处理。
      • 替换确实有效。但是如果链接中的关键字会发生什么?例如这是我的关键字它将断开链接
      • @Adelphia,好吧,让我们给他一些代码,其中有潜在的隐藏缺陷。
      • 一个简单的问题值得一个简单的答案。
      猜你喜欢
      • 2015-10-14
      • 2011-01-26
      • 2011-12-20
      • 2014-02-13
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      相关资源
      最近更新 更多