How to replace a text in a string with another text using PHP ?
Last Updated :
18 Jul, 2024
A string is a sequence of one or more characters. A string is composed of characters, each of which can be replaced easily in the script. A large number of in-built PHP methods can be used to perform string replacements.
Approach 1: Using str_replace() method - The str_replace()
This method is used to replace a text in the string with another string. However, the method compares the case of the mentioned strings. The string remains unmodified in case the old string is not found with any matchings.
str_replace($oldString, $newString, $string)
Parameters:
- $oldString: It specifies the string to be searched and replaced.
- $newString: It specifies the string that we want to replace with the $oldString string.
- $string: It specifies the string or array of strings which we want to search for $oldString and replace with $newString.
Example:
PHP
<?php
// Declaring a string variable
$str = "Hi! This is geeksforgeeks";
echo("Original String : ");
echo($str."<br>");
// Old string
$str_old = "This";
// New string
$str_new = "That";
// Replacing part of string
$final_str = str_replace($str_old,$str_new,$str);
echo("Modified String : ");
echo($final_str);
?>
Output:
Original String : Hi! This is geeksforgeeks
Modified String : Hi! That is geeksforgeeks
Note: If a part of the string is found at multiple portions, each instance of the old string is replaced with the new counterpart. The following code snippet illustrates the replacement of the symbol " " with an underscore.
PHP
<?php
// Declaring a string variable
$str = "Hi! This is geeksforgeeks";
echo("Original String : ");
echo($str . "\n");
// Old string
$str_old = " ";
// New string
$str_new = "__";
// Replacing part of string
$final_str = str_ireplace($str_old,$str_new,$str);
echo("Modified String : ");
echo($final_str);
?>
Output:
Original String : Hi! This is geeksforgeeks
Modified String : Hi!__This__is__geeksforgeeks
In case, we wish to replace the string irrespective of the case in which the old string is in, the str_ireplace() method is used. The method is supported in PHP 5+. The string behaves in a similar manner as compared to the str_replace() method.
Syntax:
str_ireplace($oldString, $newString, $string)
Parameters:
- $oldString: The string to locate in the string.
- $newString: The string to replace the old string with.
- $string: The specified string.
PHP
<?php
// Declaring a string variable
$str = "Hi! This is geeksforgeeks";
echo("Original String : ");
echo($str . "<br>");
// Old string
$str_old = "GEEKSFoRGEEks";
// New string
$str_new = "GFG";
// Replacing part of string
$final_str = str_ireplace($str_old,$str_new,$str);
echo("Modified String : ");
echo($final_str);
?>
Output:
Original String : Hi! This is geeksforgeeks
Modified String : Hi! This is GFG
Approach 3: Using preg_replace()
Using preg_replace() in PHP, replace text in a string based on a regular expression pattern. It allows for flexible and precise replacements, making it suitable for complex matching and substitutions.
Example:
PHP
<?php
$string = "Hello, World!";
$newString = preg_replace('/World/', 'PHP', $string);
echo $newString;
?>
Approach 4: Using substr_replace() method
The substr_replace() method is used to replace a part of a string with another string. This function is useful when you know the position and length of the substring you want to replace.
Example: In this example, we will use the substr_replace method.
PHP
<?php
// Declaring a string variable
$str = "Hello, World!";
echo("Original String : ");
echo($str . "\n");
// Replacement string
$replacement = "PHP";
// Starting position
$start = 7;
// Length of the substring to be replaced
$length = 5;
// Replacing part of string
$final_str = substr_replace($str, $replacement, $start, $length);
echo("Modified String : ");
echo($final_str);
?>
OutputOriginal String : Hello, World!
Modified String : Hello, PHP!
Approach 5: Using strtr() Method
The strtr() function in PHP is another useful method to perform string replacements. This function can replace multiple characters or substrings at once based on a mapping of replacements. It is efficient when dealing with a large number of replacements.
Example:
PHP
<?php
$originalString = "Hello World!";
$modifiedString = strtr($originalString, "eo", "ie");
echo "Original String: " . $originalString . "\n";
echo "Modified String: " . $modifiedString;
?>
OutputOriginal String: Hello World!
Modified String: Hille Werld!
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read