在另一个多字节字符串中搜索一个多字节字符串

发布于 2024-10-07 08:24:27 字数 194 浏览 0 评论 0原文

我使用这段代码在另一个 utf-8 字符串中搜索一个 utf-8 字符串:

if (strlen(mb_stristr($string1, $string2)) > 0)

但它总是返回 0!有谁知道这个问题有更好的解决方案吗?两个字符串都可能是 unicode 和非 unicode 字符的某种组合!

I use this code to search for one utf-8 string in another utf-8 string:

if (strlen(mb_stristr($string1, $string2)) > 0)

but it always returns 0! Does anyone know any better solution to this problem? Both strings may be some combination of unicode and non-unicode characteres!

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

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

发布评论

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

评论(3

淡淡的优雅 2024-10-14 08:24:27

为什么不直接使用 mb_stripos 呢?

如果您不知道源编码,您可能需要使用 mb_detect_encoding 以及随后的 mb_convert_encoding 到将每个字符串转换为通用编码,但这应该是相当简单的。

也就是说,如果 string2 出现在 string1 的开头(即:位置零),则需要检查 false。)

即:使用...

if (mb_stripos($string1, $string2) !== false) {
    // $string2 was found within $string1
    ...
}

Why not just use mb_stripos?

If you don't know the source encoding(s) you may need to use mb_detect_encoding and subsequently mb_convert_encoding to convert each of the strings into a common encoding, but this should be fairly trivial.

That said, you need to check for false in case string2 occurs at the start (i.e.: position zero) of string1.)

i.e.: Use...

if (mb_stripos($string1, $string2) !== false) {
    // $string2 was found within $string1
    ...
}
毁梦 2024-10-14 08:24:27

如果您不使用子字符串,请不要使用 strstr (或其派生词)。您所关心的是该字符串是否存在,因此请使用 mb_stripos

if (mb_stripos($string1, $string2) !== false) {

If you're not using the substring, don't use strstr (or its derivitives). All you care about is that the string exists, so use mb_stripos:

if (mb_stripos($string1, $string2) !== false) {
初见 2024-10-14 08:24:27
if (mb_stristr($string1, $string2) !== false) echo "found $string2 in $string2";

请注意类型安全比较运算符 !==

if (mb_stristr($string1, $string2) !== false) echo "found $string2 in $string2";

Note the type safe comparison operator !==.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文