PHP strpos() Tutorial 🎯

beginner
13 min

PHP strpos() Tutorial 🎯

Welcome to our PHP strpos() tutorial! In this lesson, we'll learn about the PHP strpos() function, which helps us to find the position of a substring within a string. This function is extremely useful when working with text data in PHP.

Before we dive in, let's discuss the importance of this function in real-world scenarios:

  1. Searching for keywords in large text files
  2. Finding specific content in user inputs
  3. Implementing password strength checkers

Understanding strpos() πŸ“

The strpos() function is a built-in PHP function that returns the position of the first occurrence of a substring within a string. If the substring is not found, it returns FALSE.

php
string strpos ( string haystack , mixed needle [, int offset ] )
  • haystack: The string in which we want to find the substring.
  • needle: The substring we're looking for.
  • offset (Optional): The position at which we should start the search.

πŸ’‘ Pro Tip: strpos() function is case-sensitive.

Example 1: Basic Usage βœ…

Let's see how we can use strpos() to find the position of a substring within a string:

php
<?php $text = "Welcome to CodeYourCraft!"; $substring = "Craft"; $position = strpos($text, $substring); echo "The position of the substring '$substring' is: $position"; ?>
Quick Quiz
Question 1 of 1

What will be the output of the above code?

Example 2: Using Offset βœ…

We can also start our search from a specific offset using the third argument in the strpos() function:

php
<?php $text = "Welcome to CodeYourCraft!"; $substring = "Your"; $offset = 11; $position = strpos($text, $substring, $offset); echo "The position of the substring '$substring' is: $position"; ?>
Quick Quiz
Question 1 of 1

What will be the output of the above code?

Quiz Time 🎯

  1. Which of the following functions helps to find the position of a substring within a string in PHP? A: strfind() B: strindex() C: strpos() Correct: C

  2. Is the strpos() function case-sensitive? A: Yes B: No Correct: A

  3. If strpos() does not find the substring, what does it return? A: -1 B: 0 C: FALSE Correct: C

  4. What does the third argument in strpos() function represent? A: Substring to search B: Haystack C: Offset at which to start searching D: Length of the substring Correct: C

  5. How can we find the position of a substring from a specific offset using strpos() function? A: By providing the offset as the second argument B: By providing the offset as the third argument C: By providing the substring as the third argument Correct: B