How to Finds the first occurrence of a string inside another string (case-insensitive) in PHP ?


There are multiple methods to find the first occurrence of a string inside another string (case-insensitive) in PHP:

Method 1: Using stripos() function The stripos() function finds the position of the first occurrence of a string inside another string (case-insensitive). It returns the position of the first occurrence of the string if found, and false otherwise.

Example:

$string = "The quick brown fox jumps over the lazy dog";
$find = "FOX";
$pos = stripos($string, $find);
if ($pos === false) {
  echo "String '$find' not found in '$string'";
} else {
  echo "String '$find' found in '$string' at position $pos";
}

Output:

String 'FOX' found in 'The quick brown fox jumps over the lazy dog' at position 16

Method 2: Using stristr() function The stristr() function finds the first occurrence of a string inside another string (case-insensitive). It returns the substring starting from the first occurrence of the string if found, and false otherwise.

Example:

$string = "The quick brown fox jumps over the lazy dog";
$find = "FOX";
$sub = stristr($string, $find);
if ($sub === false) {
  echo "String '$find' not found in '$string'";
} else {
  echo "Substring '$sub' found in '$string'";
}

Output:

Substring 'fox jumps over the lazy dog' found in 'The quick brown fox jumps over the lazy dog'

Method 3: Using preg_match() function The preg_match() function searches a string for a pattern and returns true if the pattern is found, and false otherwise. We can use a regular expression with the i modifier to make the search case-insensitive.

Example:

$string = "The quick brown fox jumps over the lazy dog";
$find = "FOX";
if (preg_match("/$find/i", $string)) {
  echo "String '$find' found in '$string'";
} else {
  echo "String '$find' not found in '$string'";
}

Output:

String 'FOX' found in 'The quick brown fox jumps over the lazy dog'


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.