w3resource

PHP String Exercises: Replace multiple characters from a string

PHP String: Exercise-23 with Solution

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

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/php-string-exercise-23.php