How to check if a string contains a specific sub string?

To check if a string contains a specific substring in PHP, you can use functions like strpos(), str_contains() (PHP 8+), or substr_count(). The most common approach is using strpos() which returns the position of the first occurrence of a substring.

Using strpos()

The strpos() function returns the position of the substring or false if not found −

<?php
    $str_1 = "thisisasample";
    $str_2 = "asample";
    
    if (strpos($str_1, $str_2) !== false) {
        echo "The substring is present within the string.";
    } else {
        echo "The substring is not present within the string.";
    }
?>
The substring is present within the string.

Using str_contains() (PHP 8+)

A more straightforward method available in PHP 8 and later −

<?php
    $str_1 = "Hello World";
    $str_2 = "World";
    
    if (str_contains($str_1, $str_2)) {
        echo "Substring found!";
    } else {
        echo "Substring not found!";
    }
?>
Substring found!

Case-Insensitive Search

Use stripos() for case-insensitive substring checking −

<?php
    $str_1 = "Hello World";
    $str_2 = "WORLD";
    
    if (stripos($str_1, $str_2) !== false) {
        echo "Substring found (case-insensitive)!";
    } else {
        echo "Substring not found!";
    }
?>
Substring found (case-insensitive)!

Comparison

Method PHP Version Case Sensitive Return Type
strpos() All versions Yes Position or false
stripos() All versions No Position or false
str_contains() 8.0+ Yes Boolean

Conclusion

Use strpos() !== false for compatibility across PHP versions, or str_contains() for cleaner code in PHP 8+. Always use strict comparison (!==) with strpos() to avoid false positives when the substring is found at position 0.

Updated on: 2026-03-15T09:00:44+05:30

784 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements