Google News
logo
PHP Program to Replace text within a string - str_replace()
The `str_replace()` function is used to replace all occurrences of a string with another string within a given string.

The syntax of the `str_replace()` function is as follows:
str_replace(search, replace, subject, count)​

 

* `search`: Required. Specifies the string to search for.

* `replace`: Required. Specifies the string to replace the search string with.

* `subject`: Required. Specifies the string to search in.

* `count`: Optional. A variable that will hold the number of replacements done.


Here is an example of using `str_replace()` function to replace a text within a string :
Program :
<?php
    $str = "I love PHP, PHP is my favorite programming language!";
    $new_str = str_replace("PHP", "JavaScript", $str);
    echo $new_str;
?>
Output :
I love JavaScript, JavaScript is my favorite programming language!
In this example, the `str_replace()` function replaces all occurrences of the string `"PHP"` with the string `"JavaScript"` in the original string `$str`.

The resulting string is stored in the variable `$new_str`, which is then printed to the screen using the `echo` statement.