Please wait

Searching through Strings

In the previous lesson, we talked about the various functions for mutating a string. This lesson will focus on functions for searching through a string. PHP provides several functions to search through strings and find the positions of substrings.

Here are a few:

  • strpos(): Finds the position of the first occurrence of a substring in a string. The function is case-sensitive.
  • stripos(): Same as strpos(), but case-insensitive.
  • strrpos(): Finds the position of the last occurrence of a substring in a string. The function is case-sensitive.
  • strripos(): Same as strrpos(), but case-insensitive.
  • str_contains(): Checks if a string contains a specific substring. Returns TRUE if the substring is found and FALSE otherwise.
  • str_starts_with(): Checks if a string starts with a specific substring. Returns TRUE if the string starts with the substring and FALSE otherwise.
  • str_ends_with(): Checks if a string ends with a specific substring. Returns TRUE if the string ends with the substring and FALSE otherwise.

String Character Indexes

In PHP, strings are sequences of characters. For example, the string "Hello, world!" is a sequence of 11 characters. You can think of each character as being in a particular position, starting from 0. So, in "Hello world", 'H' is at position 0, 'e' is at position 1, and so on.

String Indexes
String Indexes

Characters in a string are indexed in PHP, starting from 0. This means you can access individual characters in a string using their index, much like you would with an array.

Here's an example:

$str = "HELLO WORLD";
echo $str[6];  // Outputs: W

In this case, $str[6] refers to the 8th character of the string (because indexing starts at 0), which is 'W'. Understanding this concept is essential as PHP's functions rely on these indexes to perform searches.

String Position

Let's start with the strpos, stripos, strrpos, and strripos functions. The strpos(), stripos(), strrpos(), and strripos() functions are used to find the position of one string inside another. Each follows slightly different rules.

These functions have the same parameters that look like this:

strpos(string $haystack, string $needle, int $offset = 0): int|false

Parameters

  • $haystack: This is the first parameter, and it is required. This is the string where you are looking for the occurrence of another string. This is where you are searching.
  • $needle: This is the second parameter, and it is also required. This is the string that you want to find within the haystack. If the needle is not a string, it is converted to an integer and applied as the ordinal value of a character.
  • $offset: This is the third parameter, and it is optional. It allows you to specify the position in the haystack string to start searching from. It must be specified in the number of characters from the beginning of the string, not the array index. If this parameter is not provided, the search starts from the beginning of the haystack.

strpos()

The strpos() finds the position of the first occurrence of a string (the "needle") inside another string (the "haystack"). It is case-sensitive.

Here, strpos() has found that "world" first appears in "Hello, world!" at position 7 (remember, counting starts from 0).

$haystack = "Hello, world!";
$needle = "world";
$position = strpos($haystack, $needle);
 
echo $position; // Outputs: 7

strpos() with offset

Consider the string "Hello, world! I love this world!", and we want to find the second occurrence of the word "world". Here's how we can use strpos() with an offset to do this

In this example, we first find the position of the first occurrence of "world", which is at position 7. Then we use this position to calculate the offset for the second strpos() call. We add the length of the search string ("world") to the first position, so we start searching just after the first occurrence of "world". The second occurrence of "world" is found at position 27.

$text = "Hello, world! I love this world!";
$search = "world";
 
// Find the position of the first occurrence of "world"
$first_position = strpos($text, $search);
 
// Find the position of the second occurrence of "world"
// We start searching just after the first occurrence
$second_position = strpos($text, $search, $first_position + strlen($search));
 
echo $second_position;  // Outputs: 27

stripos()

Same as strpos(), but case-insensitive. This means it treats 'A' and 'a' as the same.

Even though we searched for "world" in lowercase, stripos() found "World" in uppercase at position 7.

$haystack = "Hello, World!";
$needle = "world";
$position = stripos($haystack, $needle);
 
echo $position; // Outputs: 7

strrpos()

Finds the position of the last occurrence of a string inside another string. It is case-sensitive.

Here, strrpos() found that "world" last appears at position 13.

$haystack = "Hello, world, world!";
$needle = "world";
$position = strrpos($haystack, $needle);
 
echo $position; // Outputs: 13

strripos()

Same as strrpos(), but case-insensitive.

Here, strripos() found "world" (despite the different case) last appearing at position 13.

$haystack = "Hello, World, world!";
$needle = "WORLD";
$position = strripos($haystack, $needle);
 
echo $position; // Outputs: 13

Searching for substrings

There are functions available for searching through strings for a substring called str_contains(), str_starts_with(), and str_ends_with(). These functions are used to check if a string (the "haystack") contains, starts with, or ends with another string (the "needle"). They are used for basic search operations in PHP.

All three functions have the same parameters.

str_contains(string $haystack, string $needle): bool

Parameters

  • $haystack: This is the first parameter, and it is required. This is the string where you are looking for the occurrence of another string; essentially, it's where you're performing the search.
  • $needle: This is the second parameter, and it is also required. This is the string that you're trying to find within the haystack. You can also pass a number, and it will be converted to a string before the search. The needle is case-sensitive.

These functions are beneficial when you need to look for a specific pattern in your string, and you are only interested in whether or not the pattern exists, not where it exists. Note that these functions were introduced in PHP 8.0. If you're using an older version of PHP, you would have to use different functions or techniques to achieve the same results.

Let's break them down one by one.

str_contains()

This function checks if a substring exists within a string. If the substring is found anywhere in the string, it returns true. If not, it returns false.

$myString = "Hello, world!";
$findMe   = "world";
 
if (str_contains($myString, $findMe)) {
    echo "The string 'world' was found in the string";
} else {
    echo "The string 'world' was not found in the string";
}

str_starts_with()

This function checks if a string starts with a particular substring. If the string begins with the substring, it returns true. If not, it returns false.

$myString = "Hello, world!";
$startsWith = "Hello";
 
if (str_starts_with($myString, $startsWith)) {
    echo "The string starts with 'Hello'";
} else {
    echo "The string does not start with 'Hello'";
}

str_ends_with()

This function checks if a string ends with a specific substring. If the string ends with the substring, it returns true. If not, it returns false.

$myString = "Hello, world!";
$endsWith = "world!";
 
if (str_ends_with($myString, $endsWith)) {
    echo "The string ends with 'world!'";
} else {
    echo "The string does not end with 'world!'";
}

Key Takeaways

  • Stringsare sequences of characters that can be accessed by index, starting from 0.
  • You can find the length of a string using the strlen() function.
  • Functions without "i" (like strpos() and strrpos()) are case-sensitive, while those with "i" (like stripos() and strripos()) are case-insensitive.
  • Functions: str_contains(), str_starts_with(), and str_ends_with() are new functions available from PHP 8.0 onwards that provide a more intuitive interface for checking if a string contains a specific substring or starts or ends with a particular substring.

Comments

Please read this before commenting