PHP str_contains() Function

The str_contains() function helps to search the string into another, or for easy understanding, it searches a word, letter or phrase in the sentence. It returns Boolean, so the response will always be either true or false.

Example 1:

Let’s understand it by an example.

$response = str_contains("iphone", "e");

// Output: bool(true)

In this example, we have a string in which we need to check if it contains the alphabet letter “e”. To do that, we passed the “iphone” string as the first argument and the “e” string as the second argument into the str_contains() function. In the response we got a Boolean value true, which is because the alphabet letter “e” exists in the iphone string.

The str_contains() has the ability to check case sensitivity of the value. Let’s test it by capitalizing the alphabet letter “e”.

$response = str_contains("iphone", "E");

// Output: bool(false)

As you can see, we passed the capital alphabet letter “E” and in the response we got a false value which means str_contains() searches value in the string with case sensitivity.

Example 2:

In this example, we will be searching for a word in the sentence using the str_contains() function.

$sentence = "Coder Advice aims to provide best tutorials.";

$response = str_contains($sentence, "best");

// Output: bool(true)

In the above script, the str_contains() function checks if the string value “best” exists in the provided sentence. In the response, the function returns true because the “best” string exists in the sentence and also case sensitivity of the value matches with the value that str_contains() found in the sentence.

Related Posts

Tags: PHP, PHP-Functions,