【发布时间】: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