Skip to content
Related Articles

Related Articles

Improve Article

How to replace String in PHP ?

  • Last Updated : 30 Apr, 2021
Geek Week

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.

We can replace the string with other by using PHP str_replace().

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 geeks 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 geeks 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 geeks in the string with value - 1
echo str_replace("Geeks",1,$string);
?>

Output:

1 for 1



My Personal Notes arrow_drop_up
Recommended Articles
Page :