Remove Characters At Start And End Of A String In PHP

In a previous article about how you can remove whitesapce from a string I spoke about using the functions ltrim() and rtrim(). These work by passing in a string and they will remove the whitespace. Using the ltrim() function it will remove the whitespace from the start of the string, using the * rtrim()* function will remove the whitespace from the end of the string. But you can also use these functions to remove characters from string. These functions take a second parameter that allows you to specify what characters to remove.

// This will search for the word start at the beginning of the string and remove it
ltrim($string, 'start');  

// This will search for the word end at the end of the string and remove it
rtrim($string, 'end');

Remove Trailing Slashes From String

A common use for this functionality is to remove the trailing slash from a URL. Below is a code snippet that allows you to easily do this using the rtrim() function.

function remove_trailing_slashes( $url )
{
     return rtrim($url, '/');
}

A common use for the ltrim() function is to use it to remove leading zeros from a string.


function remove_leading_zeros( $number )
{
    return ltrim($number, '0');
}

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring