0

How to build and/or modify generic URLs on Drupal/Symfony?

For example, having at the input an URL like: http://some.url/with?param1=value1#fragment I would like to be able to manipulate any parts of the url including:

  • cut off the query (search) part
  • add more query parameters
  • change the path part
  • replace domain
  • add/change fragment
  • etc

I couldn't find anything appropriate in Drupal or Symfony.

Onkeltem
  • 1,889
  • 1
  • 18
  • 27

2 Answers2

0

In Drupal 8 there is lib/Drupal/Core/Url.php class which provide some methods to get/set parameters

Availables methods to setting the route parameters:

setRouteParameters($parameters)
setRouteParameter($key, $value)

Availables methods to set the route options:

setOptions($options)
setOption($name, $value)

How to use the setParameter method:

/**
* @var Drupal\Core\Url $url
*/
$url->setRouteParameter('arg_0', $arg0);
Mohamed Ben HEnda
  • 2,686
  • 1
  • 30
  • 44
0

With Symfony 3.3 you can use Request::create($url):

use Symfony\Component\HttpFoundation\Request;

$url = 'http://some.url/with?param1=value1#fragment'
$req = Request::create($url)

Then you can call

$req->getQueryString() // param1=value1
$req->getHost() // some.url
$req->getSchemeAndHttpHost() // http://some.url
$req->getBaseUrl() // /with

Ref http://api.symfony.com/3.3/Symfony/Component/HttpFoundation/Request.html

I don't think this class provides any setter for host/param/path so you can do the following:

str_replace($req->getHost(), 'new-host.com', $url) // change host

About the hash fragment #fragment, it doesn't seem to be available on server-side (see Get fragment (value after hash '#') from a URL in php).

Flo
  • 356
  • 1
  • 11