Press "Enter" to skip to content

How to Replace a String in PHP?

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

Vinish Kapoor

Hi, I am a full stack developer and writing about development. I document everything I learn and help thousands of people. foxinfotech.in is created, written, and maintained by me; it is built on WordPress, and hosted by Bluehost. Connect with me on Facebook, Twitter, GitHub, and get notifications for new posts.

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *