str_replace

Description

This function returns a string or an array with all occurrences of
search in subject
replaced with the given replace value.

If you don't need fancy replacing rules (like regular expressions), you
should always use this function instead of preg_replace().

Parameters

If search and replace are
arrays, then str_replace() takes a value from each array
and uses them to search and replace on subject. If
replace has fewer values than
search, then an empty string is used for the rest of
replacement values. If search is an array and
replace is a string, then this replacement string is
used for every value of search. The converse would
not make sense, though.

If search or replace
are arrays, their elements are processed first to last.

search

The value being searched for, otherwise known as the needle.
An array may be used to designate multiple needles.

replace

The replacement value that replaces found search
values. An array may be used to designate multiple replacements.

subject

The string or array being searched and replaced on,
otherwise known as the haystack.

If subject is an array, then the search and
replace is performed with every entry of
subject, and the return value is an array as
well.

// Outputs F because A is replaced with B, then B is replaced with C, and so on...// Finally E is replaced with F, because of left to right replacements.$search = array('A', 'B', 'C', 'D', 'E');$replace = array('B', 'C', 'D', 'E', 'F');$subject = 'A';echo str_replace($search, $replace, $subject);

Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.

If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace:

If you need to replace a string in another, but only once but still in all possible combinations (f.e. to replace "a" with "x" in "aba" to get array("xba", "abx")) you can use this function:<?phpfunction getSingleReplaceCombinations($replace, $with, $inHaystack){$splits = explode($replace, $inHaystack);$result = array(); for ($i = 1, $ix = count($splits); $i < $ix; ++$i) {$previous = array_slice($splits, 0, $i);$next = array_slice($splits, $i);

$combine = array_pop($previous) . $with . array_shift($next);$result[] = implode($replace, array_merge($previous, array($combine), $next)); } return $result;}var_dump(getSingleReplaceCombinations("a", "x", "aba")); // result as mentioned above?>It may not be the best in performance, but it works.

Notes:1) To get round the Replacement Order Gotcha, the comma is also replaced with its code equivalent: &#44;2) You can adapt the $replace section to suit your needs: swap out the &nbsp; code with <br/> or replace comma and space with &nbsp;&middot;&nbsp; etc.

As an effort to remove those Word copy and paste smart quotes, I've found that this works with UTF8 encoded strings (where $text in the following example is UTF8). Also the elipsis and em and en dashes are replaced.

There is an "invisible" character after the â€ for the right side double smart quote that doesn't seem to display here. It is chr(157).

I was working with MySQL and displaying the title to things on the web page. I'd written a script to ensure single and double quotes were removed from the title. I used

$title = str_replace( "'", "", $title );

and

$title = str_replace( '"', "", $title );

But still the single and double quotes continued. So I wrote a bit of code to print out each character separated by a dash. Like so:

for( $i=0; $i<strlen($title); $i++ ){ echo "$i-"; }

echo "<br>\n";

This displayed:

m-y-c-o-m-p-a-n-y- b-b-&-#-3-9-;-s

Which made me go "Oh! I get it."

The MySQL function real_escape_string modifies the single quotes to be &#39; and double quotes as &#34; These still show up as single and double quotes under HTML and most importantly -

JAVASCRIPT sees the &#34; and &#39; as actual single or double quotes. So if you are passing arguments to a function you have to get rid of them or else you will get an error on trying to call a given function. Example:

<a href="javascript:func1('mycompany bbs&#39;s")'">

becomes

<a href="javascript:func1('mycompany bbs's');">

Which then will give you an error because there is a single quote inside of the single quoted string. HOWEVER, the

So remember! If you are trying to remove single and double quotes and are using MySQL and MySQL's real_escape_string() function that you might be having single and double quotes hanging around which are defined as &#39; and &#34; but which show up as single and double quotes as well as causing problems in your Javascripts.

Maybe obvious to veteran PHP programmers but less so to novice PHP programmers is the fact that this is invalid:<?phpstr_replace($search, $replace, $subject, 1);?>At a glance it appears to be a reasonable request, until you realize that the fourth parameter must be a variable in order to be passed as a reference. A replacement:<?phpstr_replace($search, $replace, $subject, $temp = 1);// or$temp = 1;str_replace($search, $replace, $subject, $temp);?>

I found a pretty low tech solution to avoid the "gotcha" without worrying about the array order of how things are replaced. I could not "order" the replacement array easily because it was being read from a database table.

Anyway if you add an identifiable token to each replaced word, then just filter this out at the very end, no nested search terms are found. I just dynamically add the %% after the first char of each word before pumping it into the str_ireplace function.

As previous commentators mentioned, when $search contains values that occur earlier in $replace, str_replace will factor those previous replacements into the process rather than operating solely on the original string. This may produce unexpected output.

In the above code, the $search and $replace should replace each occurrence in the $subject with the next letter in the alphabet. The expected output for this sample is 'BCDEF'; however, the actual output is 'FFFFF'.

Since 'A' is the only letter in the $search array that appears in $subject, one would expect the result to be 'B'; however, replacement number $n does *not* operate on $subject, it operates on $subject after the previous $n-1 replacements have been completed.

The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.

<?php/*** When using str_replace(...), values that did not exist in the original string (but were put there by previous* replacements) will be replaced continuously. This string replacement function is designed replace the values* in $search with those in $replace while not factoring in prior replacements. Note that this function will* always look for the longest possible match first and then work its way down to individual characters.** The "o" in "stro_replace" represents "original", indicating that the function operates only on the original string.** @param array $search list of strings or characters that need to be replaced* @param array $replace list of strings or characters that will replace the corresponding values in $search* @param string $subject the string on which this operation is being performed** @return string $subject with all substrings in the $search array replaced by the values in the $replace array*/function stro_replace($search, $replace, $subject){ return strtr( $subject, array_combine($search, $replace) );}

"If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though. "

I think one important (and not at all vaguely theoretical) use-case is completely ignored here. Take, for example, the way the PDO handles parameter replacement.

If we have the following query:"SELECT * FROM my_table WHERE (id = ? AND my_column = ? AND other_column = ?);"The "?"s should be replaced by each successive variable in a $parameters array. That is EXACTLY the use case for "search" being a value and "replace" being an array.

Considering that this is not only a real-world example but also part of a core PHP functionality I find it very strange that it's dismissed so easily here.

I was looking for a str_replace function supporting callbacks. As I didn't found one I wrote one my own. Works exactly like str_replace, but the replace parameter is a callback or an array of callbacks (instead of string/strings in str_replace). The callback function accepts two arguments, the string that is being replaced and the count of the replacement being done.

Fast function to replace new lines from a given string. This is interesting to replace all new lines from e. g. a text formatted in HTML retrieved from database and printing it without the unnecessary new lines. This results in slightly faster rendering in the Web browser.