Ever wanted to change “Hello World” to “Hello Universe” with a snap? In PHP, you can **easily replace words or characters** inside a string using str_replace()
, preg_replace()
, and other functions. Let’s dive in! 🚀
🔹 Basic String Replacement with str_replace()
The str_replace()
function replaces all occurrences of a word or character inside a string.
<?php $text = "I love cats! Cats are awesome!"; $search = "cats"; $replace = "dogs"; $new_text = str_replace($search, $replace, $text); echo $new_text; ?>
Output: I love dogs! Dogs are awesome!
Note: str_replace()
is case-sensitive, so “Cats” (uppercase) won’t be replaced unless specified.
🔹 Replacing Multiple Words at Once
You can replace multiple words by passing arrays as parameters.
<?php $text = "Roses are red, violets are blue."; $search = array("red", "blue"); $replace = array("green", "yellow"); $new_text = str_replace($search, $replace, $text); echo $new_text; ?>
Output: Roses are green, violets are yellow.
🔹 Case-Insensitive Replacement with str_ireplace()
If you want to replace text regardless of case, use str_ireplace()
.
<?php $text = "I love PHP, php is great!"; $search = "php"; $replace = "JavaScript"; $new_text = str_ireplace($search, $replace, $text); echo $new_text; ?>
Output: I love JavaScript, JavaScript is great!
Difference: Unlike str_replace()
, str_ireplace()
doesn’t care if “php” is lowercase or uppercase. It replaces all!
🔹 Advanced Replacements with preg_replace()
Need to replace words **with patterns**? Use preg_replace()
(supports regex). Let’s replace all digits with “X”.
<?php $text = "My phone number is 123-456-7890."; $pattern = "/\d/"; // \d matches any digit $replace = "X"; $new_text = preg_replace($pattern, $replace, $text); echo $new_text; ?>
Output: My phone number is XXX-XXX-XXXX.
🎯 Key Takeaways
str_replace()
→ Replaces text (case-sensitive).str_ireplace()
→ Replaces text (case-insensitive).preg_replace()
→ Uses regex patterns for advanced replacements.
📝 Practice Time!
Try replacing random words! Maybe change “Monday” to “Friday” and make the week shorter! 🤣