How Does strpos() Work In PHP?

Lyndi CastrejonLyndi Castrejon
2 min read

What Is strpos()?

strpos() is a built-in function in PHP that is used to find the position of the first occurrence of a substring within a string.

Understanding strpos() And Its Arguments

strpos() accepts three arguments:

  1. The first argument is the string that will be searched. In this case, we are passing in "racecar".

  2. The second argument is the substring that we are looking for within the string that will be searched. In this case, "car".

Using strpos() Without An Offset Value

In the example below, we are only using two parameters so strpos() will begin searching for "car" at the beginning of the string, "racecar".

$pos = strpos("racecar", "car");
echo $pos;
// output: 4

The strpos() function returns the position where the substring, "car", was found within "racecar" (4). If nothing had been found, then strpos() would have returned false.

Setting An Offset Value For strpos()

  1. The last parameter is optional. It allows you to set the position where the function should begin searching for the substring. Otherwise, the search would start from the beginning of the string.

So, setting an offset value (the third parameter) would look something like this:

$pos = strpos("banana", "an", 2);
echo $pos;
// 3

Notice how the program returns 3 instead of 1. This is because we have told strpos() to begin from index, 2. Skipping over the beginning of the string, "ba" in "banana", and beginning at the "n" caused strpos() to miss the (actual) first occurrence of "an". Instead, the first occurrence of "an" that strpos() encounters is at index 3.

How Can strpos() Be Used?

In another post, we created a password generator. We used the strpos() function to check whether a particular character is present in user input. This determined what kind of characters could be used to create a random password.

Input Validation

strpos() can be a helpful tool when validating user input. In the below example, strpos() is being used to validate a user email.

$email = "example@email.com";

if (strpos($email, "@") === false) {
    echo "Invalid email address.";
}

strpos() checks if the "@" is present within the string. This is one form of validation needed to determine if the user has typed in a valid email address.

Closing Thoughts

The strpos() function in PHP is a versatile tool that can be used for a variety of purposes, including input validation, string manipulation, and security.

Given the right use case, strpos() can be a powerful tool. By using it effectively, we can create more robust and secure applications, while reducing the likelihood of bugs and errors in our code.

0
Subscribe to my newsletter

Read articles from Lyndi Castrejon directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lyndi Castrejon
Lyndi Castrejon