Scout APM is PHP application performance monitoring designed for developers. With tracing logic that ties issues back to the line of code causing them, you can pinpoint n+1 queries, memory leaks, and other abnormalities in real time so you can knock them out and get back to building a great product. Start your free 14-day trial today and get the performance insight you need in less than 4 minutes.

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 two weeks 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