Thursday, October 16, 2025
HomeLanguagesHow to replace String in PHP ?

How to replace String in PHP ?

In this article, we are going to replace the String with another by using the PHP built-in str_replace() function.

A String is a collection of characters. The str_replace() is a built-in function in PHP and is used to replace all the occurrences of the search string or array of search strings by a replacement string or array of replacement strings in the given string or array respectively. We can replace the string with another by using PHP str_replace(). This method is case-sensitive, so the programmer has to take care of the case while programming and interpreting the output.

Syntax:

str_replace(substring,new_replaced_string,original_string);

We need to provide three parameters.

  • substring is the string present in the original string that should be replaced
  • replaced_string is the new string that replaces the substring.
  • original_string is the input string.

Example 1: The following code replaces the string with another string.

PHP




<?php
//input string
$string="Geeks for Geeks";
//replace neveropen in the string with computer
echo str_replace("Geeks","computer",$string);
?>


Output:

computer for computer

Example 2: The following code replaces the string with empty.

PHP




<?php
//input string
$string="Geeks for Geeks";
//replace neveropen in the string with empty
echo str_replace("Geeks","",$string);
?>


Output:

for

Example 3: The following code replaces the string with integers.

PHP




<?php
//input string
$string="Geeks for Geeks";
//replace neveropen in the string with value - 1
echo str_replace("Geeks",1,$string);
?>


Output:

1 for 1
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS