str_replace()
str_replace( array|string $search, array|string $replace, string|array $subject, int &$count = null ): string|array
The str_replace()
function takes four arguments:
$search
the search string (also called needle), you can use an array to search multiple keywords.$replace
the replacement string, you can use an array for multiple replacements.$subject
the string (or array) to search through.$count
(optional) if this argument is specified, the$count
variable will be set to the number of replacements performed.
This function returns a new string (or array) with all instances of the $search
string replaced with the $replace
string.
Example: Replace every underscore with a space.
<?php $subject = 'My_website_name_is:'; echo str_replace ('_', ' ', $subject); //Prints: My website name is:
Example: Delete or replace all newlines
In the following example, the first argument $search
is an array containing different types of linebreak escape sequences. If either escape sequence is found in the subject string, it’s replaced by the second argument.
<?php $subject = 'The first line the second line, and third line.'; $search = ["\r\n", "\r", "\n"]; echo str_replace ($search, '', $subject); /*Prints: The first line the second line, and third line. */
Example: Get the number of replacements performed
<?php $subject = 'My_website_name_is:'; //Prints: My website name is: echo str_replace('_', ' ', $subject, $count) . '<br>'; //Prints: 3 echo $count;
The str_replace()
function is case-sensitive, too perform a case-insensitive search and replace, use str_ireplace()
.
str_ireplace()
The str_ireplace()
function works same as the str_replace()
function, the only difference is that stri_replace()
is not case sensitive when searching for a string.
<?php $str = 'Welcome to my Website'; $search = 'my website'; $replace = 'BrainBell.com'; //Does not replace the string $str echo str_replace ($search, $replace, $str); //Prints: 'Welcome to Website' /* works, because str_ipreplace ignore the case when searching*/ echo str_ireplace ($search, $replace, $str); //Prints: 'Welcome to BrainBell.com'
Replace multiple strings
Another way to use str_replace()
is to replace multiple strings all at the same time. The following example demonstrates how to use the str_replace()
function with arrays:
<?php $str = 'Nos. 1. 2. 3. 4. 5.'; $search = [1,2,3,4,5]; $replace = ['i','ii','iii','iv','v']; echo str_replace ($search, $replace, $str, $count); //Prints: Nos. i. ii. iii. iv. v. echo $count; //Prints: 5
The str_replace()
function matches elements of the $search
array and replaces them with corresponding elements of the $replace
array.
Example: Delete all unwanted characters
<?php $string = "To be, or not to be; that's the question?!"; $search = ['.', ',', ':', ';', '!', '?']; $replace= ''; echo str_replace($search, $replace, $string); //Prints: To be or not to be that's the question
Manipulating substrings: