foreach strpos问题。在另一个字符串中查找字符串
我正在努力让这个脚本发挥作用。
这个想法是,如果输入字符串 ($query)
不以 '/t'
开头并且包含 $trigger
单词之一,设置了 $error
。
我无法让它工作,我也不知道为什么。
<?php
$error = false;
$triggers = array('sell', 'buy', 'trade', 'trading');
$query = 'buying stuff';
if (!empty($query)) {
if (substr($query, 0, 2) != '/t') {
foreach ($triggers as $trigger) {
if (strpos($query, $trigger)) {
$error = true;
}
}
}
}
if ($error) {
echo "fail";
}
else {
echo "pass";
}
?>
这应该触发了错误,但似乎没有。我做错了什么?
I'm trying to get this script to work.
The idea is that if the input string ($query)
doesn't start with '/t'
AND contains one of the $trigger
words, an $error
is set.
I can't get this to work and I'm not sure why.
<?php
$error = false;
$triggers = array('sell', 'buy', 'trade', 'trading');
$query = 'buying stuff';
if (!empty($query)) {
if (substr($query, 0, 2) != '/t') {
foreach ($triggers as $trigger) {
if (strpos($query, $trigger)) {
$error = true;
}
}
}
}
if ($error) {
echo "fail";
}
else {
echo "pass";
}
?>
That should have triggered the error but it doesn't seem to be. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果函数
strpos
无法找到字符串,则返回false
。另请注意,如果在开头找到搜索字符串,则返回0
。更改
为
If the function
strpos
fails to find the string it returnsfalse
. Also note that if the search string is found at the very beginning a0
is returned.Change
to
更改此设置以
检查 strpos 的工作原理
change this to
checkout how strpos works
问题是:
如果在索引 0 处找到字符串,则计算结果为 0,这会导致 IF 语句为 false
所以使用
(strpos($query,$trigger) !== false )
here is the problem :
This evaluates to 0 if string is found at index 0, which causes IF statement to be false
so use
(strpos($query,$trigger) !== false )
请使用“
break
”关键字并进行适当的检查。希望有帮助。
Please use the "
break
" keyword, along with the proper checking.Hope it helps.