Current Location: Home> Latest Articles> Comprehensive Guide to PHP String Search Methods with Examples

Comprehensive Guide to PHP String Search Methods with Examples

M66 2025-11-02

PHP String Search Methods

There are multiple ways to search strings in PHP, each suitable for different scenarios. The following sections explain the commonly used methods along with example code.

strpos()

Purpose: Finds the first occurrence of a specified substring in a string. Returns false if not found.
Syntax: strpos(string, substring, offset)
Parameters:

  • string: The string to search in
  • substring: The substring to find
  • offset: Optional, specifies the position to start searching, default is 0

Example:

$string = "Hello World";
$substring = "World";
$pos = strpos($string, $substring);
if ($pos !== false) {
    echo "Substring found at position $pos";
} else {
    echo "Substring not found";
}

stripos()

Purpose: Similar to strpos() but performs a case-insensitive search.
Syntax: stripos(string, substring, offset)
Parameters are the same as strpos().

strrpos()

Purpose: Finds the last occurrence of a specified substring in a string. Returns false if not found.
Syntax: strrpos(string, substring, offset)
Parameters are the same as strpos().

stristr()

Purpose: Searches for a specified substring in a string and returns the portion of the string starting from the substring, case-insensitive. Returns false if not found.
Syntax: stristr(string, substring, ignore_case)
Parameters:

  • string: The string to search in
  • substring: The substring to find
  • ignore_case: Optional, whether to ignore case, default is false

strstr()

Purpose: Similar to stristr() but case-sensitive.
Syntax: strstr(string, substring, ignore_case)
Parameters are the same as stristr().

By using these methods, developers can choose the appropriate function based on actual requirements and handle PHP string searches efficiently.