Have you ever lost your keys and spent hours searching for them? 😫 Well, searching for text in PHP strings is way easier than that! 🥳
PHP provides built-in functions to find specific words or characters inside a string. Let’s explore them! 🚀
🔹 Finding a Substring with strpos()
The strpos()
function finds the position of the first occurrence of a substring in a string. If the substring exists, it returns the position (starting from 0). If not, it returns false
.
<?php $text = "I love PHP programming!"; $search = "PHP"; $position = strpos($text, $search); if ($position !== false) { echo "'$search' found at position $position!"; } else { echo "'$search' not found!"; } ?>
Output: 'PHP' found at position 7!
📝 Example 1: Case Sensitivity in strpos()
strpos()
is case-sensitive! So, searching for “php” (lowercase) won’t match “PHP” (uppercase).
<?php $text = "I love PHP programming!"; $search = "php"; // lowercase $position = strpos($text, $search); if ($position !== false) { echo "'$search' found at position $position!"; } else { echo "'$search' not found!"; } ?>
Output: 'php' not found!
Solution: Use stripos()
instead (it’s case-insensitive).
🔹 Case-Insensitive Search with stripos()
If you don’t care about uppercase or lowercase, use stripos()
instead.
<?php $text = "I love PHP programming!"; $search = "php"; // lowercase $position = stripos($text, $search); if ($position !== false) { echo "'$search' found at position $position!"; } else { echo "'$search' not found!"; } ?>
Output: 'php' found at position 7!
🔹 Checking If a String Contains a Word with str_contains()
(PHP 8+)
If you only want a yes or no answer, use str_contains()
(introduced in PHP 8).
<?php $text = "The quick brown fox jumps over the lazy dog."; $word = "fox"; if (str_contains($text, $word)) { echo "Yes! '$word' is in the sentence!"; } else { echo "Nope, '$word' is missing!"; } ?>
Output: Yes! 'fox' is in the sentence!
🔹 Checking If a String Starts or Ends with a Word (PHP 8+)
PHP 8 also introduced str_starts_with()
and str_ends_with()
.
Let’s check if a sentence starts with “Hello” or ends with “world!”
<?php $text = "Hello, PHP world!"; if (str_starts_with($text, "Hello")) { echo "Yes! It starts with 'Hello'!"; } else { echo "No, it doesn't start with 'Hello'."; } echo "<br>"; // Line break if (str_ends_with($text, "world!")) { echo "Yes! It ends with 'world!'"; } else { echo "No, it doesn't end with 'world!'"; } ?>
Output:
Yes! It starts with 'Hello'!
Yes! It ends with 'world!'
🎯 Key Takeaways
strpos()
→ Finds the position of a substring (case-sensitive).stripos()
→ Finds the position (case-insensitive).str_contains()
→ Checks if a string contains a word (PHP 8+).str_starts_with()
→ Checks if a string starts with a word (PHP 8+).str_ends_with()
→ Checks if a string ends with a word (PHP 8+).
📝 Practice Time!
Try searching for words in your own sentences! Maybe check if a string contains “pizza” because, let’s be honest, that’s all we really care about! 🍕😂