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
}