In SQL we have NOT LIKE %string%
I need to do this in PHP.
if ($string NOT LIKE %word%) { do something }
I think that can be done with strpos()
But can’t figure out how…
I need exactly that comparission sentence in valid PHP.
if ($string NOT LIKE %word%) { do something }
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
You can use the PHP strpos() function to get the position of the first occurrence of a substring in a string. The function will return false if it cannot find the substring.
Using str_containsThe str_contains is a new function that was introduced in PHP 8. This method is used to check if a PHP string contains a substring. The function checks the string and returns a boolean true in case it exists and false otherwise. However, keep in mind that str_contains is case-sensitive.
The is_string() function checks whether a variable is of type string or not. This function returns true (1) if the variable is of type string, otherwise it returns false/nothing.
if (strpos($string, $word) === FALSE) { ... not found ... }
Note that strpos()
is case sensitive, if you want a case-insensitive search, use stripos()
instead.
Also note the ===
, forcing a strict equality test. strpos CAN return a valid 0
if the 'needle' string is at the start of the 'haystack'. By forcing a check for an actual boolean false (aka 0), you eliminate that false positive.
Use strpos
. If the string is not found it returns false
, otherwise something that is not false
. Be sure to use a type-safe comparison (===
) as 0
may be returned and it is a falsy value:
if (strpos($string, $substring) === false) { // substring is not found in string } if (strpos($string, $substring2) !== false) { // substring2 is found in string }
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