开发者

Search for a specific string within another string with PHP

I need to search a string for any occurances of another string in PHP. I have some co开发者_JAVA技巧de 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.


When checking for boolean FALSE in php, you need to use the === operator. Otherwise, when a string match is found at the 0 index position of a string, your if condition will incorrectly evaluate to true. This is mentioned explicitly in a big red box in the php docs for strpos().

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:

while (list($key, $val) = each($keyword)) {
  $pos = strpos($location, $val);
  if($pos === false) { // use === instead of ==
    echo "allow";
  } else {
    echo "deny";
    exit;
  }
}

Update:

With the new information you've provided, I've rewritten the logic:

function isAllowed($location) {
    $keywords = array('blah', 'another-restricted-word', 'yet-another-restricted-word');
    foreach($keywords as $keyword) {
        if (strpos($location, $keyword) !== FALSE) {
            return false;
        }
    }
    return true;
}

$location = 'http://blah.com/';
echo isAllowed($location) ? 'allow' : 'deny';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜