In this example we will try to replace "Today" to "Tomorrow" in the string: "Today is the first day of the month".
So, to do it step by step, we need to tell php what text it will search for, and with what text it will be replaced, and in what sring it will search.
PHP script:
$newstring = str_replace('Today','Tomorrow','Today is the first day of the month') ;
echo $newstring ;
?>
$newstring = str_replace('Today','Tomorrow','Today is the first day of the month, and Today is 9/1/2008') ;
echo $newstring ;
?>
$newstring1 = str_replace('Today','Tomorrow','today is 9/1/2008') ;
echo $newstring1 ;
echo '<br />' ;
$newstring1 = str_ireplace('Today','Tomorrow','today is 9/1/2008') ;
echo $newstring1 ;
?>
Tomorrow is 9/1/2008 // the str_ireplace works well, "today" was replaced
But what if you need to do many replaces for different searches ? In php you can do mutiple replaces in one, let's say for example in the string: My name is Jack and I'm 28. You would like to replace Jack to Smith and 28 to 43, so here you can use two str_replace function, one to replace Jack to Smith and one to replace 28 to 43.
But a beautiful tool in php is that you can do that in one replace function. You need to create two array: an array for the searches and an array for the replaces:
PHP Code:
$newstring1 = str_replace('Jack','Smith','My name is Jack and I\'m 28') ;
$newstring2 = str_replace('28','43', $newstring1 ) ;
echo $newstring2 ; // My name is Smith and I'm 43
echo '<br />' ;
//The new tool:
$searches = array('Jack' , '28' );
$replaces = array('Smith' , '43' );
$newstring = str_replace( $searches , $replaces ,'My name is Jack and I\'m 28') ;
echo $newstring ;
?>
My name is Smith and I'm 43 // the new tool: all replaces in one.
You can also in php do the same multiple replaces to replace different words to one word, it's the same as the last script, but we will not need aa array for replaces, but only an array for searches.
For example if you have a string: "I need 3 books, 2 copybooks and 4 pens", and you need to replace all "3" and "2" and "4" to 5 , you will do it just like the following:
PHP Code:
$searches = array('3' , '2' , '4');
$newstring = str_replace( $searches , ' 5 ' ,'I need 3 books, 2 copybooks and 4 pens') ;
echo $newstring ;
?>