How to use the str_replace() and str_split() functions in PHP. 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
// 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
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