Reusable Function to Parse Domain from a given URL

Hi everyone!
I justed started my first kirby project and so far the basics are just fine. But because I am really a php newbie, I have two question:

  1. What would be the best way to parse the domain from a given URL?
  2. And where should I put this function to use it over and over agaian in different posts?

My website is pretty simple: it’s like a tumblr blog where I collect links ti blogposts, quotes, etc. on a specific topic. At the moment there is just one home page where all the posts (I use custom post types, too) are shown (no detail views needed so far) and about page. The home page template collects the posts that are all filed under a posts-directory. For this I use in the home.php template:

foreach($pages->find('posts')->children()->visible()->flip() as $post):

Because I use custom post types, the entries have a slighty different markup. But every post has a footer with a link to the original source. Here I would like to “shorten“ the URL output by parsing the domain from the URL, e.g.
    should return

I tried

$shorturl = str_ireplace('www.', '', parse_url($post->referenceurl(), PHP_URL_HOST));

and it works fine. But I am not sure how to use snippets or other kirby “tools” to clean my markup and to not write this over and over again …

Thanks for your help!

You could put that as a function into /site/plugins from where it is accessible anywhere.

Thanks for your answer, @texnixe!

After some usual trial and error on my way into the php basics I now have something like this:

function parseddomain($sourceurl) {
   $shorturl = str_ireplace('www.', '', parse_url($sourceurl, PHP_URL_HOST));

   echo 'Source: <a href="'.$sourceurl.'" target="_blank">'.$shorturl.'</a>';

And in my template I write:


Besides the naming etc., what could be improved?

You could also use the URL class from the toolkit and might end up with cleaner code:

Thanks a lot! I will have a look at the URL class, too. So many things to learn and to discover …