English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

Usage and Examples of PHP str_replace() Function

PHP String String Functions Manual

The str_replace() function is used to replace specified characters in a string (case-sensitive).

Syntax

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

Definition and Usage

Used to replace a string with another string. The function returns a string or array. The string or array is the result after all the searches in subject are replaced by replace.

Return Value

It returns a string or array with the replacement value

Parameter

Serial NumberParameters and Description
1

find

Required. It specifies the string to be searched

2

replace

Required. It specifies the value to be replaced in find

3subject

Required. The array or string to be replaced

4

count

Optional. It counts the number of replacements.

Online example

Try the following example, string replacement, array, array elements have different numbers of replacement:

<?php
//String replacement, replace w3codebox is replaced by www.w3codebox
echo str_replace("w3codebox","www.w3codebox","oldtoolbag.com,$count);
echo"<br>";
echo "The number of replacements is:".$count;
echo"<br>";
//Replace elements in the replacement array.
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$replacement_count));
echo"<br>";
echo "The number of replacements is:".$replacement_count;
echo"<br>";
//The number of elements in the replacement and the replaced array are different
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>
Test and see‹/›

Output result

www.oldtoolbag.com
The number of replacements is:1
Array
(
    [0]=>blue
    [1]]=>pink
    [2]]=>green
    [3]]=>yellow
)
The number of replacements is:1
Array
(
    [0]=>B
    [1]]=> 
    [2]]=>!
)

PHP String String Functions Manual