PHP奇怪的位运算符对字符串的影响

5

更新...已转移到新问题

好的,阅读了PHP文档后,现在这些位运算符就清楚了,但是,啊,这是什么?

#dump1
var_dump('two identical strings' | 'two identical strings'); // mind the |
// string(21) "two identical strings"

#dump2
var_dump('two identical strings' ^ 'two identical strings'); // mind the ^
// string(21) ""

为什么#dump2显示长度为21,但是没有字符?

在Notepad++中复制字符串时,内部没有任何字符的迹象,那么为什么strlen > 0呢?这让我感到困惑,因为Notepad++可以显示某种位级别(至少我认为这些是位级别,如果我错了请纠正我)的字符,参见图片: enter image description here

这实际上是以下代码的结果:

$string = 'i want you to compare me with an even longer string, that contains even more data and some HTML characters, like € ' ^ 'And I am going to add some HTML characters, like € again to this side and see what happens'; // mind the ^
var_dump(htmlentities($string)); // had to add htmlentities, otherwise &gt; (<) characters are added in this case, therefore messing up the output - Chrome force closes `<body>` then
// string(101) "(NA'TAOOGCP MI<<m-NC C IRLIHYRSAGTNHEI   RNAEAAOP81#?"

我希望能看到与#dump2相关的问题得到回答,提前感谢!


在实验过程中,我发现了以下内容:

echo 'one' | 'two'; 
// returns 'o'

echo 'one' | 'twoe';
// returns 'oe'

那么,看到这两行代码只返回两个字符串中共同的字母,我认为它进行了某种比较或其他操作:

echo 'i want you to compare me' | 'compare me with this';    
#crazy-line // returns 'koqoveyou wotko}xise me'

在撰写本文时,发生了更奇怪的事情。 我复制了返回值,并将其粘贴到帖子文本区域中,当指针位于末尾时,它实际上比应该在的位置右侧一个“空格”。 当退格时,它清除最后一个字符,但指针仍然向右移动一个“空格”。
这导致我将此值复制到Notepad ++中:
returned value inside Notepad++
嗯,正如你所看到的,在该字符串中有一个'盒子'字符,在浏览器中不显示(至少在我的Chrome上没有显示)。 是的,当这个字符从该字符串中删除(通过退格键)时,它会恢复正常 - 不再向右移动一个“空格”。
那么,首先,在PHP中这个|是什么? 为什么会出现这样奇怪的行为?
还有,这个更奇怪的字符是什么,看起来像一个方框而在浏览器中又不显示?
我非常好奇为什么会发生这种情况,因此这里有一个包含HTML实体的更长字符串的测试:
$string = 'i want you to compare me with an even longer string, that contains even more data and some HTML characters, like &euro; ' | 'And I am going to add some HTML characters, like &euro; again to this side and see what happens';
var_dump($string);
// returns string(120) "inwaota}owo}ogcopave omwi||mmncmwwoc|o~wmrl{wing}r{augcontuonwhmweimorendaweealawomepxuo characters, like € "

最后一个值包含7个“盒子”字符。


我必须问自己为什么PHP甚至有这个。 - Daniel A. White
1
@Daniel,字符串也可以是二进制数据,就像C语言中的unsigned char*数据类型一样。我想在某些情况下,您可能希望对它们执行位运算。 - Matthew
3个回答

7

这是一个按位或运算符。它在字符串上的行为在这里解释: http://php.net/manual/en/language.operators.bitwise.php#example-107

<?php
echo 12 ^ 9; // Outputs '5'

echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4

echo 2 ^ "3"; // Outputs 1
              // 2 ^ ((int)"3") == 1

echo "2" ^ 3; // Outputs 1
              // ((int)"2") ^ 3 == 1
?>

因为声望最低而被接受。 - tomsseisums

6

这意味着 'x' | 'a' 等价于 chr(ord('x') | ord('a')),对整个字符串也是如此。 - Matthew
也许有人嫉妒你先到了。 ;) - Matthew

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接