w3resource

PHP String Exercises: Replace multiple characters from a string


23. Replace Multiple Characters in 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 :

Flowchart: Replace multiple characters from a string

For more Practice: Solve these Related Problems:

  • Write a PHP script to replace all non-numeric symbols in a string with a space, then trim multiple spaces into one.
  • Write a PHP function to substitute specific punctuation characters with a single space in a given string.
  • Write a PHP program to use str_replace() with an array of target characters to clean a string and output the result.
  • Write a PHP script to replace each occurrence of certain symbols with a space and then capitalize the first letter of each resulting word.

Go to:


PREV : Get Characters After Last '/' in URL.
NEXT : Select First Five Words from a String.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.