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.
strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.
strpos() Function: This function helps us to find the position of the first occurrence of a string in another string. This returns an integer value of the position of the first occurrence of the string. This function is case-sensitive, which means that it treats upper-case and lower-case characters differently.
PHP's strstr() function simply takes a string to search, and a chunk of text to search for. If the text was found, it returns the portion of the string from the first character of the match up to the end of the string: $myString = 'Hello, there!'; echo strstr( $myString, 'llo' ); // Displays "llo, there!"
You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string. If the substring is not found it returns false .
How does strpos () Function work in PHP? To use the strpos () function and other related functions to it we need to have the two strings, one string will be searched into another string.
Because otherwise strpos is returning a number, and you're looking for a boolean true. Show activity on this post. strpos () does not return true when it finds a match, it returns the position of the first matching string.
The strops () is one of the popular string functions we can use as per requirements. As its name suggested it for dealing with the position in any string in PHP. Using this function, we can get the position of the string inside another string.
Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With