w3resource

PHP String Exercises: Remove trailing slash from a string


21. Remove Trailing Slash from a String

Write a PHP script to remove trailing slash from a string.

Original String : 'The quick brown fox jumps over the lazy dog///'

Visual Presentation:

PHP String Exercises: Remove trailing slash from a string

Sample Solution:

PHP Code:

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

echo rtrim($my_str, '/')."\n";
// Remove trailing slashes from the original string and output the result.
?>

Sample Output:

The quick brown fox jumps over the lazy dog

Explanation:

The above PHP code snippet takes the string 'The quick brown fox jumps over the lazy dog///' and removes any trailing slashes from it using the "rtrim()" function. The "rtrim()" function trims characters from the right side of a string. Here, it trims trailing slashes from the string, resulting in the string 'The quick brown fox jumps over the lazy dog'. Finally, it echoes out the modified string.

Flowchart :

Flowchart: Remove trailing slash from a string

For more Practice: Solve these Related Problems:

  • Write a PHP script to remove all trailing slashes from a string using rtrim() and output the cleaned string.
  • Write a PHP function to check if a string ends with one or more slashes and then remove them.
  • Write a PHP program to trim trailing directory separators from a file path and display the result.
  • Write a PHP script to use regex to remove any trailing slash characters from a string.

Go to:


PREV : Remove Part of a String.
NEXT : Get Characters After Last '/' in URL.

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.