PHP: A quick way to remove trailing slashes when working with url strings

If you’re working on an ecommerce shop, you may be frequently working with your site name as a string. For example, you might be building a custom url for a sitemap or building a url link for a specific function of your cart. Here’s a quick reference guide for some of the string manipulations you might need to do frequently.

Remove the trailing slash from a domain name

Use rtrim. Here’s how:

rtrim($url_string,’/');

Remove the http or https from the start of a string

Use preg_replace. Here’s how:

preg_replace(“/^https?:\/\/(.+)$/i”,”\\1″, $url_string);

So combining the two above, to get just www.ecommerceaustralia.net.au from http://www.ecommereaustralia.net.au/ would be:

rtrim(preg_replace(“/^https?:\/\/(.+)$/i”,”\\1″,”http://ecommerceaustralia.net.au/”),’/');

Get the domain name from a string

You might want to get the domain name from a string, without any subfolders on it. For example, you might want to know what the domain name for the string http://www.ecommerceaustralia.net.au/blog/general (or if you had a subdomain http://subdomain.yourdomain.com.au for example). Here’s how.

preg_replace(‘/^www\./i’,”,$_SERVER['HTTP_HOST']);

This entry was posted in Ecommerce General. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

* Copy this password:

* Type or paste password here:

1 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>