How to replace a part of a string in PHP?
Use the str_replace() function. It replaces all matches of a search text with a new text. The syntax is str_replace(search, replace, subject).
<?php
echo str_replace("world", "Dolly", "Hello world!") . "<br>";
// Count how many replacements were done
$text = str_replace("a", "A", "banana", $count);
echo $text . " (" . $count . " replaced)<br>";
// Case-insensitive replace
echo str_ireplace("WORLD", "PHP", "Hello world!");
?>
Output:
Tutorials Class - Output Window
Hello Dolly!
bAnAnA (3 replaced)
Hello PHP!
str_replace() is case-sensitive, use str_ireplace() when the case does not matter. To replace only by position, use substr_replace(). Related: What is the use of str_replace()?.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |