PHP str_replace()Functions

PHP String 参考手册PHP String Reference Manual

Examples

Replace the characters "world" in the string "Hello world!" with "Peter":

<?php
echo str_replace("world","Peter","Hello world!");
?>

Run example »

Definition and Usage

The str_replace() function replaces some characters in a string (case-sensitive).

This function must follow the following rules:

  • If the searched string is an array, it returns an array.
  • If the searched string is an array, it will find and replace each element in the array.
  • If you need to find and replace an array at the same time, and the number of elements to be replaced is less than the number of elements found, the excess elements will be replaced with an empty string.
  • If you are searching an array but only replacing with one string, the replacement string will apply to all found values.

Note:This function is case-sensitive. Please usestr_ireplace()function to perform a case-insensitive search.

Note:This function is binary-safe.


Syntax

str_replace(find,replace,string,count)

Parameter Description
find Required. Specifies the value to search for.
replace Required. Specifies the replacementfindvalue for the value in find.
string Required. Specifies the string to be searched.
count Optional. A variable that counts the number of replacements.

Technical Details

Return value: Returns a string or array with the replacement values.
PHP Version: 4+
Changelog: In PHP 5.0, a newcountparameter was added.

Before PHP 4.3.3, this function'sfindandreplaceparameters, when both were arrays, would cause trouble, causing emptyfindindices to be ignored when the internal pointer had not been moved toreplacethe array. Newer versions do not have this problem.

As of PHP 4.0.5, most parameters can be an array.


More Examples

Example 1

Use the str_replace() function with an array and a count variable:

<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacements: $i";
?>

Run example »

Example 2

Use the str_replace() function with fewer elements to replace than elements found:

<?php
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>

Run example »


PHP String 参考手册PHP String Reference Manual Other Extensions