开发者

PHP: IF statement works on its own, but not inside WHILE loop

The problem:

Let's say I have $keyword = a sentence entered into a search box, such as "large white boxes"

What I need to do is break this into individual words, and then test each word to make sure a * doesn't appear within the first 3 letters. (So, sen* would be ok, but se* would NOT be ok). If a * does appear in first 3 letters of any individual word, then the "if ($keyword) ..." process needs to end.

if ($keyword)  {


            $token = strtok($keyword, " ");
                while ($token != false) {
                    echo $token;
                        if (stripos($token,"*") < 3 ) {
                        return;
                        }
                    $token = strtok(" ");
                    }

...code continues...

As you can see, I am echoing each time to see it processing.

If I get rid of the 'if' code, then it outputs 'largewhiteboxes' and continues on as expected.

If I leave the 'if' code as-is, only 'large开发者_开发百科' is output, and the routine ends - even though the condition has not been met!

If I run that 'if' statement on its own, outside of the WHILE loop, it works just fine, responding true to a * in first 3 positions, and false for everything else...

What might I be doing wrong with this???


There is a giant red warning in the documentation for stripos that you should heed.

In other words, you need to check if the return value !== false before checking if it is < 3.

As an aside, why do you bother with strtok when explode(',', $keyword) is available?


This variation seems to work.

$keyword = "large white boxes";

$token = strtok($keyword, " ");

while ($token !== false) {
    echo $token;
    $pos = stripos($token, "*");
    if ($pos < 3 && $pos !== false) {
        return;
    }
    $token = strtok(" ");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜