30

Why isn't this standalone code working:

$link = 'https://google.com';
$unacceptables = array('https:','.doc','.pdf', '.jpg', '.jpeg', '.gif', '.bmp', '.png');

foreach ($unacceptables as $unacceptable) {
        if (strpos($link, $unacceptable) === true) {
            echo 'Unacceptable Found<br />';
        } else {
            echo 'Acceptable!<br />';
        }
}

It's printing acceptable every time even though https is contained within the $link variable.

dWinder
  • 11,597
  • 3
  • 24
  • 39
Daniel
  • 315
  • 1
  • 3
  • 4
  • 1
    A comment for those who can't get strpos to work: be careful not to confuse `strpos( $haystack, $needle )` with the other function `in_array( $needle, $haystack )`. As you can see, **the order of the arguments is reversed**. – Marco Panichi Feb 13 '20 at 11:27

5 Answers5

80

When in doubt, read the docs:

[strpos] Returns the numeric position of the first occurrence of needle in the haystack string.

So you want to try something more like:

// ...
if (strpos($link, $unacceptable) !== false) {

Because otherwise strpos is returning a number, and you're looking for a boolean true.

coreyward
  • 77,547
  • 20
  • 137
  • 166
14

strpos() does not return true when it finds a match, it returns the position of the first matching string. Watchout, if the match is a the beginning of the string it will return an index of zero which will compare as equal to false unless you use the === operator.

acrosman
  • 12,814
  • 10
  • 39
  • 55
8

Your failure condition is wrong.

strpos returns false if match is not found, so you need to explicitly check

if (strpos($link, $unacceptable) !== false) {
Foo Bah
  • 25,660
  • 5
  • 55
  • 79
2

Strpos always return position like you search "httpsL" in your string('https://google.com';) then it return 0th position and PHP evaluate it as false.

please see this link:(Hope its very usefull for you): http://php.net/manual/en/function.strpos.php

Manish Trivedi
  • 3,481
  • 5
  • 23
  • 29
1

strpos

function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.

So I did like this

if (strpos($link, $unacceptable) !== false) {
    //Code
}
Aniket B
  • 438
  • 1
  • 5
  • 14