The Wayback Machine - https://web.archive.org/web/20240829105115/https://www.geeksforgeeks.org/how-to-replace-string-in-php/
Open In App

How to replace String in PHP ?

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Replacing a string in PHP involves substituting parts of a string with another string. Common methods include str_replace() for simple replacements, preg_replace() for pattern-based replacements, substr_replace() for positional replacements, and str_ireplace() for case-insensitive replacements. Each method serves different use cases.

Using str_replace()

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 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

Using preg_replace()

Using preg_replace() in PHP, you can replace a string using regular expressions. This function allows for pattern-based search and replace operations.

Example

PHP
<?php
$originalString = "Hello, World!";
$pattern = "/World/";
$replace = "PHP";
$newString = preg_replace($pattern, $replace, $originalString);
echo $newString . PHP_EOL; // Output: Hello, PHP!
?>

Output
Hello, PHP!

Using strtr()

The strtr() function in PHP translates certain characters or replaces substrings based on the provided mapping array. This function is useful when you need to replace multiple substrings or characters at once.

Example:

PHP
<?php
// Original string
$originalString = "I have an apple and a banana.";

// Define the replacements in an associative array
$replacements = array(
    "apple" => "orange",
    "banana" => "grape"
);

// Use strtr() to replace substrings
$newString = strtr($originalString, $replacements);

// Output the new string
echo $newString . "\n"; // Output: I have an orange and a grape.
?>

Output
I have an orange and a grape.

Previous Article
Next Article

Similar Reads

How to replace a text in a string with another text using PHP ?
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. Table of Content Using str_replace() method - The str_replace() Using str_ireplace() method Using preg_replace()Using substr_repl
4 min read
How to replace multiple characters in a string in PHP ?
A string is a sequence of characters enclosed within single or double quotes. A string can also be looped through and modifications can be made to replace a particular sequence of characters in it. In this article, we will see how to replace multiple characters in a string in PHP. Using the str_replace() and str_split() functions in PHP.The str_rep
3 min read
How to replace a string by another string in AngularJS ?
In this article, we will see how to select a string from the text and replace it with another string using AngularJS and will understand it through the illustrations. The replace() method can be used to search the particular character(s), which is getting replaced with a specific character(s) &amp; return a new generated string. Syntax: string.repl
2 min read
Difference Between String.prototype.replace() and String.prototype.replaceAll() in JavaScript
The String.prototype.replace and String.prototype.replaceAll are frequently used to the modify strings. Understanding the differences between these methods is crucial for the effective string handling. This article explores the characteristics, applications and examples of both the replace and replaceAll methods. These are the following topics that
3 min read
How to replace all occurrences of a string using Vue.js filters ?
In this article, we are going to learn how to replace all occurrences of a particular word with some other word using filters in VueJS. Vue is a progressive framework for building user interfaces. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The f
2 min read
Less.js String replace() Function
Less.js is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is preferable since CSS is a dynamic style sheet language. LESS can be utilized by many different browsers because it is versatile. Web browsers can only use CSS that has been developed and processed using a co
3 min read
How to globally replace a forward slash in a JavaScript string ?
In JavaScript, a forward slash serves multiple purposes such as division operator, string character, etc. In this article, we will see how to globally replace a forward slash in a JavaScript string. Below are the methods used to globally replace a forward slash in a JavaScript string: Table of Content Using replace() method with a regular expressio
3 min read
Replace special characters in a string with underscore (_) in JavaScript
In this article, we will see how to replace special characters in a string with an underscore in JavaScript. These are the following method to do this: Table of Content JavaScript replace() MethodUsing Lodash _.replace() MethodJavaScript replace() MethodThis method searches a string for a defined value, or a regular expression, and returns a new st
2 min read
JavaScript string replace() Method
JavaScript replace() method is used for manipulating strings. It allows you to search for a specific part of a string, called a substring, and then replace it with another substring. What's great is that this method doesn't alter the original string, making it ideal for tasks where you want to maintain the integrity of the original data. Understand
5 min read
How to replace all dots in a string using JavaScript ?
We will replace all dots in a string using JavaScript. There are multiple approaches to manipulating a string in JavaScript. Table of Content Using JavaScript replace() MethodUsing JavaScript Split() and Join() Method Using JavaSccript reduce() Method and spread operatorUsing JavaScript replaceAll() MethodUsing JavaScript for loopUsing JavaScript m
4 min read
How to replace all occurrences of a string in JavaScript ?
Replacing all occurrences of a string in JavaScript is a common task in text processing. It involves identifying and substituting specific substrings within a larger string. This capability is crucial for tasks such as data cleaning, formatting, and transforming text in various applications. These are the following methods to replace all occurrence
3 min read
JavaScript Program to Replace Characters of a String
Given a String the task is to replace characters of String with a given String in JavaScript. Examples: Input: Str = Welcome to GfG strRepl = GfG newStr = GeeksOutput: Welcome to GeeksTable of Content Using map() &amp; split() method to replace characters from StringUsing String replace() Method to replace characters from StringUsing Regular Expres
3 min read
JavaScript URLify a given string (Replace spaces is %20)
In this article, we are going to discuss how can we URLify a given string using JavaScript. In which we will be transforming the spaces within the input strings into the "%20" sequence. The process of URLLification consists of replacing these spaces with the '%20' encoding. This task is essential for creating valid URLs, and query parameters. Examp
6 min read
Replace all Occurrences of a Substring in a String in JavaScript
In JavaScript, a string is a sequence of characters represented with quotation marks. We are given a string and we need to replace all occurrences of a substring from the given string. Table of Content Using replace() method with regular expressionUsing indexOf() and slice() methodsUsing replaceAll() methodUsing the replace() method with regular ex
2 min read
Replace Duplicate Occurrence in a String in JavaScript
JavaScript String is a sequence of characters, typically used to represent text. It is useful to clean up strings by removing any duplicate characters. This can help normalize data and reduce unnecessary bloat. There are several ways to replace duplicate occurrences in a given string using different JavaScript methods which are as follows: Table of
3 min read
Replace Specific Words in a String Using Regular Expressions in JavaScript
In this article, we are going to learn about replacing specific words with another word in a string using regular expressions. Replacing specific words with another word in a string using regular expressions in JavaScript means searching for all occurrences of a particular word or pattern within the text and substituting them with a different word
4 min read
JavaScript Program to Replace Multiple Characters in a String
We are going to learn how we can replace Multiple Characters in a String. We have to replace multiple characters in a string using the inbuilt function or any other method. Table of Content Using replace() methodUsing replaceAll() methodUsing split() and join()Using regular expression Using reduce()Using Map for ReplacementUsing Object for Characte
5 min read
TypeScript String replace() Method
The replace() method in TypeScript is used to find matches between a regular expression or a substring and a string, replacing the matched substring with a new substring or the value returned by a function. Syntaxstring.replace(regexp/substr, newSubStr/function[, flags]);Parameter: This method accepts five parameters as mentioned above and describe
2 min read
Check if a given String is Binary String or Not using PHP
Given a String, the task is to check whether the given string is a binary string or not in PHP. A binary string is a string that should only contain the '0' and '1' characters. Examples: Input: str = "10111001"Output: The string is binary.Input: str = "123456"Output: The string is not binary.Table of Content Using Regular ExpressionUsing strspn( )
5 min read
PHP Program to check a string is a rotation of another string
Given the two strings we have to check if one string is a rotation of another string. Examples: Input : $string1 = "WayToCrack", $string2 = "CrackWayTo"; Output : Yes Input : $string1 = "WillPower" $string2 = "lliW"; Output : No. The above problem can be easily solved in other languages by concatenating the two strings and then would check if the r
3 min read
How to check a string starts/ends with a specific string in PHP ?
In this article, we are going to learn how to check that a given string is starting or ending with a given specific string in PHP. We require the use of XAMPP, Netbeans to run this code. Input: "Geeks For Geeks"Starting with: "G"Output: "Geeks For Geeks Starts with String G"In PHP version 8+, there are str_starts_with(), str_ends_with() functions w
2 min read
HTML | DOM Location replace() Method
The DOM Location replace() Method in HTML is used to replace the current document with the specified one. This method is different from the assign() method as this removes the current document from the document history, therefore it is not possible to go back to the previous document using the 'back' button. Syntax: location.replace( newUrl ); Para
1 min read
Collect.js replace() Method
The replace() method is used to replace the elements of the original collection that match the given string or numeric keys. If the key given in the object matches with a key in the collection, then its value is replaced, otherwise, if the key does not match, then it is added to the collection. Syntax: collect(array).replace(object) Parameters: The
1 min read
How to replace innerHTML of a div using jQuery?
For replacing innerHTML of a div with jquery, html() function is used. Syntax: $(selector).html() Example: &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt; changing-innerhtml-using-jquery &lt;/title&gt; &lt;link href= &quot;https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css
1 min read
How to replace lowercase letters with an other character in JavaScript ?
Given a string and the task is to replace all lowercase letters from a string with the other characters in JavaScript. There are some approaches to replace the character that are described below: JavaScript replace() Method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced define
2 min read
Replace a DOM element with another DOM element in place
The task is to replace an element by another element in place using JavaScript. Below are the few methods: parentNode Property: This property returns the parent node of the defined node, as a Node object. Syntax: node.parentNode Return value: It returns a node object, which represents the parent node of a node, or null if there is no parent. replac
3 min read
How to replace plain URL with link using JavaScript ?
Given a plane URL, the task is to replace the plain URLs with the links. This problem can be solved with the help of Regular Expressions. Approach: Using RegExp and replace() MethodRegExp - This looks for the URL in the provided text.This RegExp parses the URL and puts the address to the $1 variable.After getting the URL in the text, it replaces it
2 min read
How to replace a character at a particular index in JavaScript ?
To replace a character from a string there are popular methods available, the two most popular methods we are going to describe in this article. The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index. Both methods are described below: Approach 1: Usin
4 min read
How to replace dropdown-toggle icon with another default icon in Bootstrap ?
Bootstrap provides the option of adding a dropdown to our websites. The default icon on the dropdown button is the 'downward solid arrow' logo. Even though it serves its purpose, most of the modern-day websites nowadays use Bootstrap. Therefore, the icon might look very generic to the visitor.Program: C/C++ Code &amp;lt;!DOCTYPE html&amp;gt; &amp;l
3 min read
Replace live() with on() in jQuery
The following jQuery event handler functions are basically used for attaching events to elements or selectors but are very different from each other. Before turning jQuery live() into on() function, let us first learn about the event handlers as well as their differences. jQuery live() : This jQuery function attaches a function handler for all the
8 min read