2

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.

1
  • It's simpler to use strstr() if you don't actually need the substring position. Commented Nov 17, 2010 at 6:59

1 Answer 1

2

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';
Sign up to request clarification or add additional context in comments.

1 Comment

How do I check to see if it is a match, instead of false?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.