0
0
PHPprogramming~5 mins

String replace functions in PHP

Choose your learning style9 modes available
Introduction

String replace functions help you change parts of text easily. They let you swap old words or characters with new ones.

Fix typos in user input before saving.
Change a word in a sentence automatically.
Remove unwanted characters from a string.
Update URLs or file paths in text.
Format text by replacing placeholders.
Syntax
PHP
str_replace(search, replace, subject, &count);

search is what you want to find in the text.

replace is what you want to put instead.

subject is the text you want to change.

count is optional and tells how many replacements were done.

Examples
This replaces 'cat' with 'dog' in the sentence.
PHP
$newText = str_replace('cat', 'dog', 'The cat is cute.');
This replaces 'a' with '1' and 'e' with '2' in the word 'apple'.
PHP
$newText = str_replace(['a', 'e'], ['1', '2'], 'apple');
This replaces 'is' with 'was' and counts how many times replacement happened.
PHP
$count = 0;
$newText = str_replace('is', 'was', 'This is it. This is fun.', $count);
echo $count;
Sample Program

This program shows how to replace words step by step in a sentence.

PHP
<?php
// Original text
$text = "Hello world! PHP is fun.";

// Replace 'world' with 'everyone'
$newText = str_replace('world', 'everyone', $text);

// Replace multiple words
$newText2 = str_replace(['PHP', 'fun'], ['Python', 'awesome'], $newText);

// Show results
echo $text . "\n";
echo $newText . "\n";
echo $newText2 . "\n";
?>
OutputSuccess
Important Notes

str_replace is case-sensitive. Use str_ireplace for case-insensitive replacement.

If search is an array, replace should be an array of the same size.

The original string is not changed unless you assign the result back to it.

Summary

Use string replace functions to swap parts of text easily.

You can replace single or multiple words or characters at once.

Remember to assign the result to a variable to keep the changes.