w3resource

PHP String Exercises: Remove part of a string

PHP String: Exercise-20 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to remove all leading zeroes from a string.
Next: Write a PHP script to remove trailing slash from a 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-20.php