How to Replace a String in PHP?

How to Replace a String in PHP?

  • PHP
  • 2 mins read

In this tutorial, you will learn how to replace a string in PHP. PHP supports a predefined function str_replace(), which is used to replace a string or strings instead of another string or strings in text.

Here is the syntax of str_replace() function for replacing one string:

str_replace(string which will be replaced, string which will be inserted, text)

Here we are writing a common program with str_replace() function:

<html>
<body>
<?php
$a="well come to Delhi";
$b=str_replace("well","Well",$a);//here "well" will be replaced by "Well"
echo $b;
?>
</body>
</html>

Output: Well come to Delhi

How to replace more than one word instead of other words using str_replace() function?

Here we will use two arrays. One is for searching values, and another is for replacement values.
Now we will give an example of replacing more than one word.

<html>
<body>
<?php
$a="kolkata is in India,It is the capital of India";
$b=str_replace(array("kolkata","India"),array("KOLKATA","West Bengal"),$a);//here "kolkata" will be replaced by "KOLKATA" and "India" will be replaced by "West Bengal"
echo $b;
?>
</body>
</html>

Output: KOLKATA is in West Bengal, It is the capital of West Bengal