How to use the preg_replace() function in PHP 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
// 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
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.
Contact Us