Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
How to read each character of a string in PHP ?
Next article icon

How to replace multiple characters in a string in PHP ?

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace. The array is constructed by first defining a sequence of characters to replace in the string and then passing the same sequence into the str_split() function to convert it into an array. The second parameter is the character which replaces the array of characters found in the string and the third parameter is the string on which this operation is performed. 

Example: In this example, the characters to be replaced are ‘\\/:*?”<>|+-‘ and the character replacing these characters is the empty character ”.

PHP
<?php  // Declaring the original string $orig_string = '\"\Ge+eks/f*o:r-G/ee*ks';  print("Original string: "); print($orig_string."\n"."<br>");  // Replacing multiple characters using the // str_replace and str_split functions $new_string = str_replace(str_split(     '\\/:*?"<>|+-'), '', $orig_string);  print("Modified string: "); print($new_string); ?> 

Output:

Original string: \"\Ge+eks/f*o:r-G/ee*ks
Modified string: GeeksforGeeks

Using the preg_replace() function in PHP

The preg_replace() function is also used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace enclosed within ~[ and ]~. The second and third parameters are exactly the same as the previous approach.

Example: In this example, the characters to be replaced are ‘\\/:*?”<>|+-‘ and the character replacing these characters is the empty character ”.

PHP
<?php      // Declaring the original string $orig_string = '\"\Ge+eks/f*o:r-G/ee*ks';  print("Original string: "); print($orig_string."\n"."<br>");  // Replacing multiple characters using // the preg_replace function $new_string = preg_replace(         '~[\\\\/:*?"<>|+-]~', '', $orig_string);  print("Modified string: "); print($new_string); ?> 

Output:

Original string: \"\Ge+eks/f*o:r-G/ee*ks
Modified string: GeeksforGeeks

Using strtr Function

The strtr function in PHP efficiently replaces multiple characters in a string. It takes a translation table as input, where keys are characters to be replaced and values are their replacements. This approach simplifies the process of character substitution.

Example:

PHP
<?php $string = "Hello World!"; $translation_table = array('H' => 'J', 'W' => 'M'); $new_string = strtr($string, $translation_table); echo $new_string; // Outputs: Jello Morld! ?> 

Output
Jello Morld!

Using str_replace() with Arrays

The str_replace function can also be used with arrays for both search and replace parameters. This allows replacing multiple characters or sequences of characters with different replacements in one go. This approach is useful when you need to perform multiple replacements where each character or sequence has a specific replacement.

Example: In this example, we will replace specific characters in the original string with corresponding replacements defined in the arrays.

PHP
<?php  // Declaring the original string $orig_string = 'Hello World! PHP is fun.';  // Characters to be replaced $search = array('H', 'W', 'P', 'f');  // Replacement characters $replace = array('J', 'M', 'R', 'b');  print("Original string: "); print($orig_string . "\n" . "<br>");  // Replacing multiple characters using the str_replace function with arrays $new_string = str_replace($search, $replace, $orig_string);  print("Modified string: "); print($new_string); ?> 

Output
Original string: Hello World! PHP is fun. <br>Modified string: Jello Morld! RJR is bun. 


Next Article
How to read each character of a string in PHP ?

R

rajatsandhu2001
Improve
Article Tags :
  • Geeks Premier League
  • PHP
  • Web Technologies
  • Geeks-Premier-League-2022
  • PHP-function
  • PHP-Questions

Similar Reads

  • How to read each character of a string in PHP ?
    A string is a sequence of characters. It may contain integers or even special symbols. Every character in a string is stored at a unique position represented by a unique index value. Here are some approaches to read each character of a string in PHP Table of Content Using str_split() method - The st
    4 min read
  • How to remove the first character of string in PHP?
    Remove the very first character of a given string in PHP Examples: Input : GeeksforgeeksOutput : eeksforgeeksInput :, Hello geek!Output : Hello geek!Explanation: In PHP to remove characters from the beginning we can use ltrim but in that, we have to define what we want to remove from a string i.e. r
    3 min read
  • How to get the position of character in a string in PHP ?
    In this article, we will get the position of the character in the given string in PHP. String is a set of characters. We will get the position of the character in a string by using strpos() function. Syntax: strpos(string, character, start_pos) Parameters: string (mandatory): This parameter refers t
    2 min read
  • How to replace String in PHP ?
    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
    3 min read
  • How to insert a line break in PHP string ?
    In this article, we will discuss how to insert a line break in a PHP string. We will get it by using the nl2br() function. This function is used to give a new line break wherever '\n' is placed. Syntax: nl2br("string \n");where the string is the input string. Example 1: PHP Program to insert a line
    2 min read
  • How to get the last character of a string in PHP ?
    In this article, we will find the last character of a string in PHP. The last character can be found using the following methods. Using array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is "Akshit" Its length is 6, i
    2 min read
  • How to Remove Pattern with Special Character in String in R?
    Working with strings in R often involves cleaning or manipulating text data to achieve a specific format. One common task is removing patterns that include special characters. R provides several tools and functions to handle this efficiently. This article will guide you through different methods to
    3 min read
  • How to Replace Part of a String in MySQL?
    To replace a part of a string in MySQL we use the REPLACE function. MySQL provides this method to manipulate string data in the tables. In this article, we are going to see how we can update a part of the string with some other value in MySQL. Understanding this can enable string manipulation in a m
    4 min read
  • How to extract Numbers From a String in PHP ?
    Extracting numbers from a string involves identifying and isolating numerical values embedded within a text. This process can be done using programming techniques, such as regular expressions, to filter out and retrieve only the digits from the string, ignoring all other characters. Here we have som
    3 min read
  • How to check if a String contains a Specific Character in PHP ?
    In PHP, determining whether a string contains a specific character is a common task. Whether you're validating user input, parsing data, or performing text processing, PHP provides several methods to check for the presence of a particular character within a string efficiently. Here are some common a
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences