Search code examples
phpurlyii2yii-url-manager

Yii 2. Replace "+" in URL to "-"


What do I want

I want to replace "+" in URL-attrib to "-". I'm using Yii 2.

I want working URLs with "-". URL::to(...) generates URL with "-". I want user to see in his browser address panel with "-".

Example:

This

 <siteneme>/hospital/U.S.A./Cleveland+Clinic

To this

<siteneme>/hospital/U.S.A./Cleveland-Clinic

What do I have

Here is my web.php

 'urlManager' => [
            'enablePrettyUrl'     => true,
            'showScriptName'      => false,
            'enableStrictParsing' => false,
            'rules'               => [

                //Site controller, hospital action
                'hospital/<location>/<name>' => 'site/hospital',

                '<controller:\w+>/<action:\w+>'               => '<controller>/<action>',

                //removing 'controller' form URL
                '<alias:index|search|detail|result|hospital>' => 'site/<alias>',
            ],

        ],

This is how generates URL in view :

   <?= Url::to([
                'hospital', 
                'location' => $item->locations['name'],
                'name'     => $item->attributes['name'] ]); ?>

Solution

  • + is generated because of urlencoding the space character.

    If you want to only change + to - you can do something like that:

    <?= Url::to([
        'hospital', 
        'location' => str_replace(' ', '-', $item->locations['name']),
        'name'     => str_replace(' ', '-', $item->attributes['name'])
    ]); ?>
    

    This will change every space in name to - (in the example here both location and name is changed) and urlencoded - is not modified.