PHP str_replace()
Published Jun 3, 2022Updated Jul 28, 2023
Contribute to Docs
The str_replace() function returns a string with occurrences of a specified substring replaced by another string. The function can operate on scalar strings or arrays.
Syntax
str_replace($search, $replace, $base, $count)
$searchis thestringbeing searched for in$base. It can be astringor anarray. Each element will be searched for if it’s anarray.$replaceis thestringused for replacing the$searchterm. If$searchand$replacearearrays, each$searchitem will be replaced by the corresponding item in$replace. If$replaceitems run out, an emptystringwill be used for the remaining values. If$searchis anarrayand$replaceis astring, then the$replacevalue will be used for all$searchitems.$baseis thestring(s) being searched. If it is anarray, the replacements will be made to everystringin thearray, and the function will return anarrayof the modifiedstrings.$countis an optionalint. If included, it will be set to the number of replacements performed.
Example
The following example uses the str_replace() function to replace the word "book" with "lot" in the given sentence. Then the echo command prints this sentence to the console:
<?phpecho str_replace("book", "lot", "I read a book.");?>
The example will result in the following output:
I read a lot.
Codebyte Example
This example uses the str_replace() function with strings.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PHP on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours