PHPโ€™s strpos() is a handy function used to find the position of a substring (the โ€œneedleโ€) inside another string (the โ€œhaystackโ€). Itโ€™s super useful for input validation, text processing, and more.


๐Ÿง  Syntax

strpos(string $haystack, string $needle, int $offset = 0)
  • $haystack: The full string youโ€™re searching in.
  • $needle: The part youโ€™re looking for.
  • $offset (optional): Where to start the search from.

๐Ÿ” What It Returns

  • If found โ†’ returns the position (starting at 0).
  • If not โ†’ returns false.

โœ… Always use !== false for checks. Why? Because a return value of 0 means the match is at the very start โ€” and 0 == false would be misleading.


๐Ÿ“Œ Example

$text = "Hello, world!";
$search = "world";
$pos = strpos($text, $search);

if ($pos !== false) {
  echo "Found at position: $pos";
} else {
  echo "Not found.";
}

Output: Found at position: 7


โš ๏ธ Things to Note

  • Case-sensitive: "World" โ‰  "world".
  • Binary-safe.
  • Use strict comparison to avoid false positives.

๐Ÿ’ก Use Cases

  • Checking for banned words in user input
  • Parsing logs or CSV files
  • Extracting data
  • Cleaning up messy strings

๐Ÿงช Quick Quiz

1. What does strpos() return if the needle isnโ€™t found? a) 0 b) โ€œnot foundโ€ c) false d) error message

2. Whatโ€™s the output?

$text = "This is a sample string.";
$search = "sample";
echo strpos($text, $search);

โœ… Wrap-Up

strpos() is small but mighty. Mastering it helps you write smarter string-handling code in PHP. Try it out in your next form validation or data parser!


<
Previous Post
๐Ÿ’ป Formatting Your Flash Drive Using Command Prompt: A Step-by-Step Guide
>
Next Post
๐ŸŒŸ Functions: Understanding Functions with JavaScript and Scratch