Open In App

How to replace multiple characters in a string in PHP ?

Improve
Improve
Like Article
Like
Save
Share
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.

Approach 1: 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 

Approach 2: 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 


Last Updated : 17 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads