Documentation for crwlr / url (v2.0)

Attention: You're currently viewing the documentation for v2.0 of the url package.
This is not the latest version of the package.
If you didn't navigate to this version intentionally, you can click here to switch to the latest version.

Modifying Urls

All methods that are used to get a component's value can also be used to replace or set its value. So for example if you have an array of urls, and you want to be sure that they are all on https, you can achieve this simply by setting the scheme to https for all of them in a loop.

$urls = [
    'https://www.example.com',
    'http://notsecure.example.org/foo',
    'https://secure.example.org/bar',
    'http://www.example.com/baz'
];

foreach ($urls as $key => $url) {
    $urls[$key] = Url::parse($url)->scheme('https')->toString();
}

var_dump($urls);

Output

array(4) {
  [0]=>
  string(24) "https://www.example.com/"
  [1]=>
  string(33) "https://notsecure.example.org/foo"
  [2]=>
  string(30) "https://secure.example.org/bar"
  [3]=>
  string(27) "https://www.example.com/baz"
}

Another example: your website can be reached with or without the www subdomain. Sloppy input data can easily be fixed by just assigning the same host to all of them.

$urls = [
    'https://www.example.com/stuff',
    'https://example.com/yolo',
    'https://example.com/products',
    'https://www.example.com/contact',
];

$urls = array_map(function($url) {
    return Url::parse($url)->host('www.example.com')->toString();
}, $urls);

var_dump($urls);

Output

array(4) {
  [0]=>
  string(29) "https://www.example.com/stuff"
  [1]=>
  string(28) "https://www.example.com/yolo"
  [2]=>
  string(32) "https://www.example.com/products"
  [3]=>
  string(31) "https://www.example.com/contact"
}

And that's the same for all components that are listed under the available url components.

And the query can even be set as an array:

$url = Url::parse('https://www.example.com/foo');
$url->queryArray(['param' => 'value', 'marco' => 'polo']);
echo $url;

Output

https://www.example.com/foo?param=value&marco=polo

Btw.: As you can see in the example above, you can use an Url object like a string because of its __toString() method.