使用 str_ireplace 时保留大小写吗?

发布于 2024-08-19 13:02:23 字数 451 浏览 2 评论 0原文

我正在构建一个搜索,它将用 标签包装搜索到的文本,并且此代码工作正常:

str_ireplace($q,'<span>'.$q.'</span>',$row[name]);

问题是,如果用户搜索 Tom将会显示 Tom,这很酷,但是如果他们因为 str_ireplace 而放入 tom,则会显示 tom ,这有道理吗?真正的问题是,如果有人输入 tOm aRnFeLd 虽然搜索结果正常,但美观效果实际上会显示在页面上 tOm aRnFeLd

我怎样才能保留大写字母和小写字母'两个弦的性质?有没有更好的方法来包装字符串中不区分大小写的文本?

I am building a search that will wrap the searched text with a <span> tag and I have this code working OK:

str_ireplace($q,'<span>'.$q.'</span>',$row[name]);

The problem is, if a user searches for Tom is will show Tom which is cool, but if they put in tom because of the str_ireplace it would show tom, does that make sense? The real issue is if someone entered tOm aRnFeLd although it would search OK, the aesthetics would actually show up on the page tOm aRnFeLd

How can I retain the capital letters and lower case 'ness of both strings? Is there a better way to wrap case insensitive text from a string?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

好多鱼好多余 2024-08-26 13:02:23

使用 stristr 从 haystack 中获取针,不区分大小写,

$keyword_caseRetained_all = stristr($excerpt, $keyword);

但也会返回针和 haystack 的其余部分,因此您必须使用 substr 只保留针部分。从位置 0 开始,达到关键字的长度,

$keyword_caseRetained = substr($keyword_caseRetained_all, 0, strlen($keyword) );

现在在 str_ireplace 函数中使用该变量

$excerpt = str_ireplace($keyword, '<em>'.$keyword_caseRetained.'</em>', $excerpt);

一旦知道这一点,您就可以将第 1 行和第 2 行合并在一个漂亮的老鼠巢中以缩短代码。

或者将其作为方法添加到字符串操作类中。

use stristr to get the needle from the haystack, case insensitive

$keyword_caseRetained_all = stristr($excerpt, $keyword);

but that returns the needle and the rest of haystack too, so you have to use substr to only keep the needle portion. start at position 0, get up to the length of keyword

$keyword_caseRetained = substr($keyword_caseRetained_all, 0, strlen($keyword) );

now use that variable inside the str_ireplace function

$excerpt = str_ireplace($keyword, '<em>'.$keyword_caseRetained.'</em>', $excerpt);

once you know this, you can combine lines 1 and 2 in a nice rats nest to shorten your code.

or add this as a method to a string manipulation class.

葬花如无物 2024-08-26 13:02:23
  1. 获取短语长度 strlen()
  2. 使用 stripos()
  3. 插入文本在文本的 N 个字符之后(其中 N 是点 #2 的结果)
  4. 在文本的 N+M 字符之后插入文本(其中 N 是点 #2 的结果,M 是点 #2 的结果) #1)
  5. 继续第 2-4 点(使用 strpos() 的第三个参数 - offset
  1. Get phrase length strlen()
  2. Find occurrence of phrase using stripos()
  3. Insert into text <span> after text's N character (where N is result from point #2)
  4. Insert into text </span> after text's N+M character (where N is result from point #2 and M is result from point #1)
  5. Continue points 2-4 (Using third parameter of strpos() - offset)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文