使用 PHP 在另一个字符串中搜索特定字符串
我需要在 PHP 中搜索一个字符串以查找另一个字符串的出现情况。我有一些我一直在玩的代码,但它似乎不起作用。
这是我的代码:
while (list($key, $val) = each($keyword)) {
$pos = strpos($location, $val);
if($pos == false) {
echo "allow";
exit;
} else {
echo "deny";
exit;
}
}
我已经尝试了下面的一些选项,但仍然找不到匹配项。这是我正在搜索的内容:
我需要找到:*
blah
在:
http://blah.com
似乎找不到它。该代码在常规句子中工作:
Today, the weather was very nice.
它会从句子中找到任何单词,但是当它们全部放在一起(在 URL 中)时,它似乎找不到它。
I need to search a string for any occurances of another string in PHP. I have some code that I've been playing with, but it doesn't seem to be working.
Here is my code:
while (list($key, $val) = each($keyword)) {
$pos = strpos($location, $val);
if($pos == false) {
echo "allow";
exit;
} else {
echo "deny";
exit;
}
}
I have tried some of the options below, but it still does not find the match. Here is what I'm searching:
I need to find:*
blah
In:
http://blah.com
Nothing seems to find it. The code works in regular sentences:
Today, the weather was very nice.
It will find any word from the sentence, but when it is all together (in a URL) it can't seem to find it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 php 中检查布尔值
FALSE
时,需要使用===
运算符。否则,当在字符串的0
索引位置找到字符串匹配时,您的if
条件将错误地计算为true
。这在 php 文档strpos( )
。此外,根据您在另一个答案下留下的评论,似乎您需要从允许访问的块中删除
exit
语句。将它们放在一起,我想您的代码应该如下所示:
更新:
根据您提供的新信息,我重写了逻辑:
When checking for boolean
FALSE
in php, you need to use the===
operator. Otherwise, when a string match is found at the0
index position of a string, yourif
condition will incorrectly evaluate totrue
. This is mentioned explicitly in a big red box in the php docs forstrpos()
.Also, based on a comment you left under another answer, it appears as though you need to remove the
exit
statement from the block that allows access.Putting it all together, I imagine your code should look like this:
Update:
With the new information you've provided, I've rewritten the logic: