【问题标题】:WordPress: Highlight search results - but keeping the same case as was originally on the pageWordPress:突出显示搜索结果 - 但保持与页面上最初相同的大小写
【发布时间】:2021-11-27 17:42:45
【问题描述】:

对于我的 WordPress 搜索结果页面,我添加了突出显示以显示搜索词出现在结果页面上的位置。但是替换代码会将页面文本更改为搜索词中使用的case。

例如:

Search Term:                                      remote Employee ENGAGE 
Text on Page before highlight:                    Remote employee engagement 
Resulting text after highlight replacement:       remote Employee ENGAGEment
Desired text after highlight replacement:         Remote employee engagement

这是我在 content-search.php 中使用的代码

<?php $title = str_ireplace( $s, '<span class="search-instance">'.$s.'</span>', get_the_title() ) ?>
<?php $excerpt = str_ireplace( $s, '<span class="search-instance">'.$s.'</span>', get_the_excerpt() ) ?> 
<?php echo $title; ?>   
<?php echo $excerpt; ?>

以及突出显示文本的css:

span.search-instance {
   font-weight: bold;
   background: #fffdca;
   padding: 2px;
}

有人可以提供一些关于如何完成突出显示的建议,使用不区分大小写的搜索,而且在突出显示过程中不更改页面上文本的大小写。

干杯, SunnyOz

更新:

我不认为我可以用 str_ireplace 做我想做的事。

我想我可能需要使用类似preg_replace 和一些regex 的东西允许部分匹配(即:不要限制匹配单词边界)- 但我不'不知道如何在我的代码示例中进行设置。

如果我确实需要使用preg_replace 而不是str_ireplace,我仍然可以使用一些帮助。

如何不区分大小写搜索 get_the_title() 和 get_the_excerpt() 并使用所使用的搜索词 - 使用 preg_replace?

【问题讨论】:

    标签: php wordpress search replace preg-replace


    【解决方案1】:

    试试这个

    $string = 'Test test REmotE emPloYee engAgeMent end string ';
    $keys = array('remote Employee ENGAGE');
    
    $patterns = array();
    
    foreach($keys as $key) {    
    $patterns[] = '/\b('.$key.'([^ ]*))\b/i';
    echo preg_replace($patterns, '<span class="search-instance">$0</span>', $string);
    }
    

    您的代码有什么问题,您正在寻找一个短语并进行替换。 在这种情况下,我们需要在字符串中找到一个模式,如果有东西匹配这个模式,然后用标签包装匹配。

    【讨论】:

    • 当我看到您的评论时,我正要回答我自己的问题。您绝对走在正确的轨道上,并且可能对大多数人有用,所以我接受了它作为答案。但我也会包括我自己的答案,专门针对我的代码。
    【解决方案2】:

    我确实找到了一种方法来做我想做的事。我从这个页面找到了解决方案:https://www.wpbeginner.com/wp-tutorials/how-to-highlight-the-search-terms-in-results-in-wordpress/

    这是我更改的新代码:

    <?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '<span class="search-instance">\0</span>', $title); ?>
    <?php $excerpt = get_the_excerpt(); $keys= explode(" ",$s); $excerpt = preg_replace('/('.implode('|', $keys) .')/iu', '<span class="search-instance">\0</span>', $excerpt); ?>
    

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 2016-06-25
      • 2018-03-05
      • 2020-03-29
      • 2018-04-26
      • 1970-01-01
      • 2010-10-24
      • 2016-05-29
      • 1970-01-01
      相关资源
      最近更新 更多