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_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: w3wiki

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

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!

Contact Us