PHP String Exercises: Replace multiple characters from a string
Write a PHP script to replace multiple characters from the following string.
Sample String : '\"\1+2/3*2:2-3/4*3'
Sample Solution:
PHP Code:
<?php
$my_str = '\"\1+2/3*2:2-3/4*3';
// Define the original string.
echo str_replace(str_split('\\/:*?"<>|+-'), ' ', $my_str)."\n";
// Replace all occurrences of special characters with a space in the original string and output the result.
?>
Output:
1 2 3 2 2 3 4 3
Explanation:
The above PHP code snippet replaces all special characters in the string '\"\1+2/3*2:2-3/4*3' with a space.
- str_split('\\/:*?"<>|+-') creates an array containing all the special characters to be replaced.
- str_replace() then replaces each occurrence of these special characters with a space in the original string '$my_str'.
- Finally, it echos the modified string.
Flowchart :
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP script to get the characters after the last '/' in an url.
Next: Write a PHP script to select first 5 words from the specified string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics