Question

Using the Zend Framework and the url method for the view:

$this->url(array('field1' => this, 'field2' => 'is', 'field3' => 'my example'), 'route_name');

Where route_name is the name of the url route and each field# is retrieved from the database.

I noticed that by default it changes spaces in Controller/Action names into plus sign so that what looked like:

www.example.com/this is my example

to

www.example.com/this+is+my+example

I would like to change the separatoer from + to - to have something like

www.example.com/this-is-my-example

I know that another thread: How to change the separation character of Zend Url? as documented a way to do it which I tried without success.

A thorough explanation on how to do it would be much appreciated.

EDIT2: I know where the problem lies if anyone is interested, it comes from the way the url is assemble, it uses urlencode which converts all non-alphanumeric characters expect - and _ and the spaces as +, there is no way to override that than replace the character create the url manually (as Maxime suggested) or create a custom url function replacing the characters (as suggest by aporat)...

Thanks!

Was it helpful?

Solution

If you really want to do that, you can extend the stock Zend_View_Helper_Url view helper and add your url logic into your view helper.

<?php
namespace Application\View\Helper;

 class MyUrl extends \Zend_View_Helper_Url
 {
    /**
     * Generates an url given the name of a route.
     *
     * @access public
     *
     * @param  array $urlOptions Options passed to the assemble method of the Route object.
     * @param  mixed $name The name of a Route to use. If null it will use the current Route
     * @param  bool $reset Whether or not to reset the route defaults with those provided
     * @return string Url for the link href attribute.
     */
     public function myUrl(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
     {

     return str_replace('+', '-', parent::url($urlOptions, $name, $reset, $encode));
     }
}

and then just load your new view helper and you're good to go:

        $helper = new \Application\View\Helper\MyUrl;
        $this->view->registerHelper($helper, 'myUrl');

OTHER TIPS

Unfortunately, you can't set anything before calling the url(...) function to achieve what you want to do. The reason is that when the URL is assembled, it uses the php urlencode(...) function.

That said, you still have many options:

1) You simply don't use the url(...) function and create your URLs manually. (Best option)

2) You create a new helper that acts like url(...) but add extra changes to the function to achieve what you want to do.

3) You take the output of the url(...) function and do a str_replace to change + with -. (I DO NOT recommend that option)

Personally, I create all my URLs manually to avoid this kind of problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top