$str='Hello to plus2net.com';
$search='Hello';
$replace='Welcome';
echo str_replace($search,$replace,$str);
Output is here
Welcome to plus2net.com
Syntax
str_replace(search,replace,main_string,count);
search:
Required: String to be searched for matching, can be an array
replace:
Required: String to be replaced if found using search string, can be an array
main_string:
Required : String on which search and replace to be applied, can be an array
count:
Optional: Stores the number of replacements performed.
Output is a string or array after performing search and replace over the input string
To replace a part of the string with another string we will use str_replace function in PHP. This function will replace all the occurrence of the string we target and will replace with the string we supply. Here is an example.
<?Php
$string="This is an example on how html is used in
developing user-friendly web sites. By using HTML we can
control the content of a page";
echo $string;
echo "<br><br>";
$string=str_replace("html","PHP",$string);
echo "<b>After replace</b> <br><br>$string";
?>
If you run the above code your will see result like this
This is an example on how html is used in developing user-friendly web sites. By
using HTML we can control the content of a page
After replace
This is an example on how PHP is used in developing user-friendly web sites. By
using HTML we can control the content of a page
We can create an array of search strings and an array or replace strings. These two array we can apply to search and replace words from the content. The matching words will be replace by matching strings from replace array.
Original String
Welcome to Plus2net.com to learn PHP, MYSQL, HTML, jquery and many more.
After replacement
Welcome to plus2net.com to learn php, MySQL, html, JQuery and many more.
Here is the code
$contents="Welcome to Plus2net.com to learn PHP, MYSQL, HTML , jquery and many more.";
echo "Original String $contents";
$search=array("Plus2net.com","PHP","jquery","HTML","MYSQL");
$replace=array("plus2net.com","php","JQuery","html","MySQL");
$contents=str_replace($search,$replace,$contents);
echo "After replacement $contents";
Highlighting the changes.
Replace the replace array with additional tags to highlight the replaced string.
We can store number of search and replacement carried out using str_replace function.
$str='Raju is a good boy and he has many good habits.';
$search='good';
$replace='bad';
echo str_replace($search, $replace, $str,$count);
echo "<br>Number of replacements = $count <br>";
Output is here
Raju is a bad boy and he has many bad habits. Number of replacements = 2