w3resource

PHP String Exercises: Remove part of a string


20. Remove Part of a String

Write a PHP script to remove part of a string.

Original String : 'The quick brown fox jumps over the lazy dog'
Remove 'fox' from the above string.

Visual Presentation:

PHP String Exercises: Remove part of a string

Sample Solution:

PHP Code:

<?php
$my_str = 'The quick brown fox jumps over the lazy dog';
// Define the original string.

echo str_replace("fox", " ", $my_str)."\n";
// Replace all occurrences of "fox" with a space in the original string and output the result.
?>

Output:

The quick brown   jumps over the lazy dog 

Explanation:

The above PHP code snippet takes the string 'The quick brown fox jumps over the lazy dog' and replaces all occurrences of the substring 'fox' with a space ' ' using the str_replace() function. The "str_replace()" function searches for a specific substring in a string and replaces all occurrences with another substring. Here, it replaces all occurrences of 'fox' with a space, resulting in the string 'The quick brown jumps over the lazy dog'. Finally, it echoes out the modified string.

Flowchart :

Flowchart: Remove part of a string

For more Practice: Solve these Related Problems:

  • Write a PHP script to search for a specific substring in a sentence and remove it, then output the modified sentence.
  • Write a PHP function to delete a target word from a given string and return the new string.
  • Write a PHP program to remove all instances of a particular substring from a sentence, ensuring correct spacing afterward.
  • Write a PHP script to use str_replace() selectively to remove only the first occurrence of a given word from a string.

Go to:


PREV : Remove Leading Zeroes from a String.
NEXT : Remove Trailing Slash 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.