php strpos无效,簡單的PHP strpos功能不起作用,為什么?

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
';

}

else {

echo 'Acceptable!
';

}

}

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

即使https包含在$ link變量中,每次打印都是可接受的。

6 个解决方案

#1

53

When in doubt, read the docs:

如有疑問,請閱讀文檔:

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

[strpos]返回haystack字符串中第一次出現needle的數字位置。

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.

因為否則strpos返回一個數字,你正在尋找一個布爾值true。

#2

7

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.

strpos()在找到匹配項時不返回true,它返回第一個匹配字符串的位置。注意,如果匹配是字符串的開頭,它將返回零索引,除非你使用===運算符,否則它將等於false。

#3

5

Your failure condition is wrong.

你的失敗情況是錯誤的。

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

如果未找到匹配,則strpos返回false,因此您需要顯式檢查

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

#4

1

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.

Strpos始終返回位置,就像您在字符串中搜索“httpsL”('https://google.com';;)然后返回第0個位置,PHP將其評估為false。

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

請看這個鏈接:(希望它對你非常有用):http://php.net/manual/en/function.strpos.php

#5

0

if (strpos($link, $unacceptable))

{

} else {

/* What you want to do when it is false */

}

#6

0

strpos

strpos

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

function可以返回布爾值FALSE,但也可以返回一個非布爾值,其值為FALSE。

So I did like this

所以我確實喜歡這個

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

//Code

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值