Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

A class to parse, build and manipulate URLs

Original – by Freek Van der Herten – 2 minute read

For several projects and other packages we need to manipulate URL's. Instead of coding the same URL class over and over again, we extracted URL manipulation to it's own package. Here are some code examples on how you can use it.

$url = Url::fromString('https://spatie.be/opensource');

echo $url->withHost('github.com')->withPath('spatie');
// 'https://github.com/spatie'

Query parameters can be retrieved and transformed:

$url = Url::fromString('https://spatie.be/opensource?utm_source=github&utm_campaign=pacakges');

echo $url->getQuery(); // 'utm_source=github&utm_campaign=pacakges'
echo $url->getQueryParameter('utm_source'); // 'github'
echo $url->withoutQueryParameter('utm_campaign'); // 'https://spatie.be/opensource?utm_source=github'

It can retrieve path segments:

$url = Url::fromString('https://spatie.be/opensource/laravel');

echo $url->getSegment(1); // 'opensource'
echo $url->getSegment(2); // 'laravel'

It implements PSR-7's UriInterface interface:

class Url implements UriInterface { /* ... */ }

The league/uri is a more powerful package than this one. The main reason our package exists, is because the alternatives require non-standard php extensions. If you're dealing with special character encodings or need bulletproof validation, you're definitely better off using league/uri.

That being said, if you need a lightweight solution, take a look at spatie/url on Github.

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every month I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments

What are your thoughts on "A class to parse, build and manipulate URLs"?

Want to join the conversation? Log in or create an account to post a comment.