PHP string contains

Question

Answers ( 1 )

    0
    2024-01-11T18:05:21+00:00

    It's about determining if a string contains a specific substring in PHP.

    In PHP, you can check if a string contains another string using various functions. Here are the most common methods:

    1. Using strpos() Function

    The strpos() function is used to find the position of the first occurrence of a substring in a string. It returns the index of the first occurrence of the substring, or false if the substring is not found.

    $string = "Hello, world!";
    $substring = "world";
    
    if (strpos($string, $substring) !== false) {
        echo "The string contains the substring.";
    } else {
        echo "The string does not contain the substring.";
    }
    

    2. Using strstr() Function

    The strstr() function is another way to check if a string contains a specific substring. It returns part of the string starting from and including the first occurrence of the substring, or false if the substring is not found.

    $string = "Hello, world!";
    $substring = "world";
    
    if (strstr($string, $substring)) {
        echo "The string contains the substring.";
    } else {
        echo "The string does not contain the substring.";
    }
    

    3. Using str_contains() Function (PHP 8+)

    In PHP 8 and later, the str_contains() function provides a more straightforward way to check for a substring. It returns true if the substring is found, and false otherwise.

    $string = "Hello, world!";
    $substring = "world";
    
    if (str_contains($string, $substring)) {
        echo "The string contains the substring.";
    } else {
        echo "The string does not contain the substring.";
    }
    

    Notes:

    • Be aware that strpos() is case-sensitive. If you need a case-insensitive search, use stripos().
    • str_contains() is available only in PHP 8 and later versions.
    • Always remember to use strict comparison (!== false) with strpos(), as it can return 0 (which is a falsy value in PHP) if the substring is at the beginning of the string.

Leave an answer