PHP Function – str_replace
The str_replace function is used to replace part of a string with another string. The syntax of this PHP function is detailed below:
<? mixed str_replace( $search, $replace, $subject, $count ); ?>
$search – This can either be a string value or an array of strings. This will be the string or strings you want to be replaced.
$replace – This can either be a string or an array of strings. These will be the value that is replaced when one of the $search items are found.
$subject – The string that will be searched and have replacements placed inside of it.
$count (optional) – The maximum number of times a replace should occur.
There are a number of reasons why you would want to use this function. One of the ways that I use str_replace is when I need to remove line breaks from the a large string that you are working with. You would do that by doing the following:
<? $input = str_replace( "\n", '', $input ); ?>
You may have noticed that I used $input as the return variable and the string that is having the replace performed on it. This is a quirk that I use in order to not have to create extra variables and you cannot pass the $input to the function as reference.