PHP 精确匹配一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8943372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Match a string exactly
提问by C0nw0nk
$check = 'this is a string 111';
if ($check = 'this is a string') {
echo 'perfect match';
} else {
echo 'it did not match up';
}
But it returns perfect match everytime instead of it did not match up... I can not seem to get the string to match the case exactly it will only work if part of the string matches up.
但它每次都返回完美匹配而不是它不匹配......我似乎无法让字符串完全匹配大小写它只有在字符串的一部分匹配时才会起作用。
If i try to complicate things a little using board code and regex patterns it becomes a nightmare.
如果我尝试使用板代码和正则表达式模式将事情复杂化一点,它就会变成一场噩梦。
if ($check = '/\[quote(.*?)\](.*?)\[\/quote\]/su') {
$spam['spam'] = true;
$spam['error'] .= 'Spam post quote.<br />';
}
So if the post only contained quote tags it would be considered spam and ditched but i can not seem to solve it perhaps my patterns are wrong.
所以如果帖子只包含引用标签,它会被认为是垃圾邮件并被丢弃,但我似乎无法解决它,也许我的模式是错误的。
回答by Nick
You need to use ==
not just =
您需要使用==
不只是=
$check = 'this is a string 111';
if ($check == 'this is a string') {
echo 'perfect match';
} else {
echo 'it did not match up';
}
=
will assign the variable.
=
将分配变量。
==
will do a loose comparison
==
会做一个松散的比较
===
will do a strict comparison
===
会做严格的比较
See comparison operatorsfor more information.
有关更多信息,请参阅比较运算符。
回答by Rob Agar
For equality comparison you want the ==
operator. =
is assignment.
对于相等比较,您需要==
运算符。=
是赋值。
if ($check = 'this is a string') {
should be
应该
if ($check == 'this is a string') {
Don't worry, we've all done it. I still do :)
别担心,我们都做到了。我仍然 :)
回答by goat
the == comparison operator will work in most cases, but fails to do an exact match in some edge cases*.
== 比较运算符在大多数情况下都可以使用,但在某些边缘情况下无法完全匹配*。
Using === operator is best.
最好使用 === 运算符。
if ($check === 'this is a string') {
An example where == works unexpectedly
== 意外工作的示例
$check = '2';
if ($check == ' 2') {
回答by meagar
You're using the assignment operator, =
, instead of the equality operator ==
.
您正在使用赋值运算符=
,而不是相等运算符==
。
You need to use
你需要使用
if ($check == 'this is a string') {
回答by dweeves
if ($check = 'this is a string')
assigns the string to $check
variable which is always defined and thus, returns always true in the if
if ($check = 'this is a string')
将字符串分配给$check
始终定义的变量,因此在 if 中始终返回 true
should be if ($check == 'this is a string')
应该 if ($check == 'this is a string')