Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Remove Characters at the Start and End of a String in PHP

DZone's Guide to

Remove Characters at the Start and End of a String in PHP

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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 to remove whitespace. Using the ltrim() function 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 a 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 a 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 remove the "http://" from a URL. Use the function below to remove both "http" and "https" from a URL:

function remove_http( $url )
{
    $url = ltrim($url, 'http://');
    $url = ltrim($url, 'https://');

    return $url;
}

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}