How can I replace a certain part of my string with another one?
Input string:
"Hello my name is Santa"
How can I change all a
's in my string with something else?
I think I need a foreach
loop, but I'm unsure how to use it.
How can I replace a certain part of my string with another one?
Input string:
"Hello my name is Santa"
How can I change all a
's in my string with something else?
I think I need a foreach
loop, but I'm unsure how to use it.
this can work also without of any of php str functions here changing your 'a' to '&' ampersand character:
Use function preg_replace()
Search & Replace
There are a few different functions/methods to replace a certain part of a string with something else, all with their own advantages.
str_replace()
method (binary safe; case-sensitive)Arguments
str_replace()
has 3 required arguments as you can see in the above definition with the correct order, all of which can take a string as also an array as argument!Search & Replace
search(string) AND replace(string) → Replaces the search string with the replace string.
search(array) AND replace(string) → Replaces all search elements with the replace string.
search(string) AND replace(array) → Throws you a notice: "Notice: Array to string conversion", because a replacement array for just one search string doesn't make sense, so it tries to convert the array to a string.
search(array) AND replace(array) → Replaces each search element with the corresponding replace element (Keys are ignored!).
search(more elements) AND replace(less elements) → Replaces each search element with the corresponding replace element (For the missing replace elements an empty string will be used).
search(less elements) AND replace(more elements) → Replaces each search element with the corresponding replace element (Unneeded replace elements are ignored).
Subject
subject(string) → Replacement is done for the subject string.
subject(array) → Replacement is done for each array element.
Code
Output
Notes
Gotcha!
Important to know is that
str_replace()
works from left to right of the array. This means it can possible replace a value which you already replaced. For example:Case insensitive
If you want to make the search case insensitive you can use
str_ireplace()
(Notice thei
for case-insensitive).Multidimensional array
str_replace()
/str_ireplace()
does NOT work for multidimensional arrays. See this manual comment for such an implementation. Of course you can also replacestr_replace()
withstr_ireplace()
for case-insensitive.If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:
strtr()
method (50% binary safe; case-sensitive)Arguments
The function either takes 3 arguments with a from and to string or it takes 2 arguments with a replacement array
array("search" => "replace" /* , ... */)
, all of which you can see in the above definition with the correct order.2 Arguments
It starts to replace the longest key with the corresponding value and does this until it replaced all
key => value
pairs. In this case the function is binary safe, since it uses the entire key/value.3 Arguments
It replaces the from argument with the to argument in the subject byte by byte. So it is not binary safe!
If the from and to arguments are of unequal length the replacement will stop when it reaches the end of the shorter string.
Subject
It doesn't accept an array as subject, just a string.
Code
Output
Notes
Gotcha!
Opposed to
str_replace()
,strtr()
does NOT replace something twice. As an example:Also if you want to replace multiple things with the same string you can use
array_fill_keys()
to fill up your replacement array with the value.Case insensitive
strtr()
is NOT case-insensitive NOR is there a case-insensitive equivalent function. See this manual comment for a case-insensitive implementation.Multidimensional array
strtr()
does opposed tostr_replace()
NOT work with arrays as subject, so it also does NOT work with multidimensional arrays. You can of course use the code above fromstr_replace()
for multidimensional arrays and just use it withstrtr()
or the implementation ofstritr()
.If you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:
preg_replace()
method (binary safe; case-sensitive)Arguments
preg_replace()
has 3 required parameters in the order shown above. Now all 3 of them can take a string as also an array as argument!Search & Replace
search(string) AND replace(string) → Replaces all matches of the search regex with the replace string.
search(array) AND replace(string) → Replaces all matches of each search regex with the replace string.
search(string) AND replace(array) → Throws you a warning: "Warning: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array", because a replacement array for just one search regex doesn't make sense.
search(array) AND replace(array) → Replaces all matches of each search regex with the corresponding replace element(Keys are ignored!).
search(more elements) AND replace(less elements) → Replaces all matches of each search regex with the corresponding replace element(For the missing replace elements an empty string will be used).
search(less elements) AND replace(more elements) → Replaces all matches of each search regex with the corresponding replace element(Unneeded replace elements are ignored).
Subject
subject(string) → Replacement is done for the subject string.
subject(array) → Replacement is done for each array element.
Please note again: The search must be a regular expression! This means it needs delimiters and special characters need to be escaped.
Code
Output
Notes
Gotcha!
Same as
str_replace()
,preg_replace()
works from left to right of the array. This means it can possible replace a value which you already replaced. For example:Case insensitive
Since the search argument is a regular expression you can simply pass the
flag i
for case-insensitive search.Multidimensional array
preg_replace()
does NOT work for multidimensional arrays.Backreference
Be aware that you can use
\\n
/$n
as backreference to your capturing groups of the regex. Where0
is the entire match and1-99
for your capturing groups.Also if the backreference is immediately followed by a number you have to use
\${n}
.Replacement / "The /e modifier is deprecated"
The replacement in
preg_replace()
can't use callback functions as replacements. So you have to usepreg_replace_callback()
. Same when you use the modifiere
and get "Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead". See: Replace preg_replace() e modifier with preg_replace_callbackIf you want to put everything together and create a function that also works for multidimensional arrays case-insensitive you can do something like this:
Loops
while
/for
/foreach
method (NOT binary safe; case-sensitive)Now of course besides all of those functions you can also use a simple loop to loop through the string and replace each
search => replace
pair which you have.But this gets way more complex when you do it binary safe, case-insensitive and for multidimensional arrays than just using the functions above. So I won't include any examples here.
Affected String
Right now all methods shown above do the replacement over the entire string. But sometimes you want to replace something only for a certain part of your string.
For this you probably want to/can use
substr_replace()
. Or another common method is to usesubstr()
and apply the replacement only on that particular substring and put the string together afterwards. Of course you could also modify your regex or do something else to not apply the replacement to the entire string.str_replace is sufficient for simple replacement jobs (such as replacing a single letter), but the use of preg_replace is generally advised (if you want something more flexible or versatile), because it's flexible and versatile. And as the 'a' is just an example...:
Or if you want multiple replacements at once:
preg_replace can, unfortunately, be quite tricky to use. I recommend the following reads: http://php.net/manual/en/function.preg-replace.php http://www.phpro.org/tutorials/Introduction-to-PHP-Regex.html
Also, if you decide to use str_replace(), and your replacement needs to be case-sensitive, you're going to need str_ireplace().
UPDATE:
To answer your question more precisely.