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)
$search
is thestring
being searched for in$base
. It can be astring
or anarray
. Each element will be searched for if it’s anarray
.$replace
is thestring
used for replacing the$search
term. If$search
and$replace
arearrays
, each$search
item will be replaced by the corresponding item in$replace
. If$replace
items run out, an emptystring
will be used for the remaining values. If$search
is anarray
and$replace
is astring
, then the$replace
value will be used for all$search
items.$base
is thestring
(s) being searched. If it is anarray
, the replacements will be made to everystring
in thearray
, and the function will return anarray
of the modifiedstrings
.$count
is 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.