Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a string contains a word in PHP?

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 } 
like image 445
Lucas Matos Avatar asked Feb 02 '12 20:02

Lucas Matos


People also ask

How do you see if a string contains a word?

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.

How do you check if a string is contained in another string PHP?

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.

Is contain string PHP?

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.

How check string is value or not in PHP?

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.


2 Answers

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.

like image 80
Marc B Avatar answered Sep 28 '22 17:09

Marc B


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 } 
like image 21
TimWolla Avatar answered Sep 28 '22 16:09

TimWolla