当针字符串包含不可见/零宽度字符时,strpos() 返回 false
为什么回报不好?
<?php
$r = "<h3>Welcome</h3>";
if (strpos($r, "Welcome") !== FALSE) {
echo "Good";
}
?>
通过对创建此帖子时被破坏的违规 unicode 字符进行硬编码来重现:
$r = "<h3>Welcome</h3>";
if (strpos($r, "\u{200C}Welcome") !== FALSE) {
echo "Good";
}
Why it is not returning good?
<?php
$r = "<h3>Welcome</h3>";
if (strpos($r, "Welcome") !== FALSE) {
echo "Good";
}
?>
Reproduce by hardcoding the offending unicode character which was destroyed when creating this post:
$r = "<h3>Welcome</h3>";
if (strpos($r, "\u{200C}Welcome") !== FALSE) {
echo "Good";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你看到那个小
框了吗?即 UTF-8 中的
E2 80 8B
,即零宽度空间。这并不存在于您的源文本中。
Do you see the little
box? That isE2 80 8B
in UTF-8, the zero-width space.And that's not present in your source text.
奇怪的是,它对我有用(请参阅 codepad):
但是,我重写了该字符串,因为在您的代码中它包含一个隐藏字符。 ;)
Strange, it works for me (see codepad):
However, I rewrote the string because in your code it contains a hidden character. ;)
你的代码应该可以工作 - 逻辑很好。
然而,那里有一个有趣的角色 - 我想你已经从某个地方复制/粘贴了这段代码?
当我将此页面上的代码复制到编辑器中时,它抱怨有一个字符无法在我的字符集中表示,并且
strpos($r, " Welcome")
变为strpos ($r,“?欢迎”)
。输入字符串不会发生这种情况,因此它们不会匹配。
Your code should work - the logic is fine.
However, there is a funny character in there somewhere - I presume you have copy/pasted this code from somewhere?
When I copy the code off this page into my editor, it complains that there is a character that cannot be represented in my character set, and
strpos($r, "Welcome")
becomesstrpos($r, "?Welcome")
.This does not happen for the input string so they won't match.