Sling Academy
Home/PHP/PHP: Check if a string contains a substring

PHP: Check if a string contains a substring

Last updated: January 09, 2024

Introduction

In PHP, working with text often involves determining if a specific sequence of characters, or substring, exists within another string. This process is essential for tasks like validating input, searching content, and processing text data.

Checking for the presence of substrings within strings is a common operation in web development. In PHP, several functions can help you reliably check whether a substring exists within a larger string. This article walks through various PHP functions, from the most straightforward methods to more complex approaches, for performing this check.

Using strpos() and stripos()

The strpos() function is one of the simplest ways to check for the presence of a substring. It finds the position of the first occurrence of a substring in a string. The function is case-sensitive, which means that searching for ‘apple’ is different from ‘Apple’. If you need a case-insensitive search, use stripos() instead.

if (strpos('Hello world', 'world') !== false) {
    echo 'The substring exists.';
} else {
    echo 'The substring does not exist.';
}

if (stripos('Hello world', 'World') !== false) {
    echo 'The substring exists, case-insentively.';
} else {
    echo 'The substring does not exist.';
}

Using strstr() and stristr()

Another way to detect a substring is using strstr() and stristr(). These functions return the part of the string starting from and including the first occurrence of the substring. If the substring is not found, they return false.

$content = 'This is a simple text';
$substring = 'simple';

if (strstr($content, $substring)) {
    echo 'The substring "' . $substring . '" exists.';
} else {
    echo 'The substring does not exist.';
}

// Case-insensitive search
if (stristr($content, $substring)) {
    echo 'The substring "' . $substring . '" exists, case-insensitively.';
} else {
    echo 'The substring does not exist.';
}

Using preg_match()

For more complex pattern matching, preg_match() utilizing regular expressions can be employed. This is particularly useful if the substring follows a specific format or pattern.

$text = 'Contact us at [email protected]';
$pattern = '/info\@[a-z]+\.com/';

if (preg_match($pattern, $text)) {
    echo 'The pattern is detected in the string.';
} else {
    echo 'Pattern not detected.';
}

Using substr_count()

If you wish to count how many times a substring appears in a string, substr_count() is the function to use. It provides the number of occurrences of the substring.

$str = 'This is the way. The way is hard but fair.';
$needle = 'way';

$count = substr_count($str, $needle);
echo 'The substring appears ' . $count . ' times.';

Working with Multibyte Strings

PHP also provides functions to handle multibyte strings, such as those containing characters from languages other than English. Functions like mb_strpos() and mb_stripos() allow for proper detection of substrings in multibyte scenarios.

$text = '这是一些中文';
$substring = '中文';

if (mb_strpos($text, $substring) !== false) {
    echo 'The multibyte substring exists.';
} else {
    echo 'The multibyte substring does not exist.';
}

Conclusion

In conclusion, PHP offers developers a variety of functions for checking the presence of substrings, providing the flexibility to select an approach that best suits the task. Whether you need a case-sensitive or insensitive search, count occurrences, or deal with multibyte strings, PHP has the tools necessary to perform these checks effectively.

Next Article: Base64 Encoding and Decoding in PHP: A Complete Guide

Previous Article: Find and Replace Substrings in PHP: A Practical Guide

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array