在 Symfony2 中用加号替换 URL 中的空格


Replace spaces by pluses in URLs in Symfony2

如果我在 Symfony2 中生成一个带有空格的 URL,例如:

example.com/some text

然后此 URL 显示在网站上,如下所示:

example.com/some%20text

如何设置用加号而不是 %20 替换空格?

在这种情况下:

example.com/some+text

我需要通用解决方案,而不是在所有 URL 中添加 |replace('%20','+')。

谢谢大家的回答,我找到了自己的解决方案。

在 MainBundle''Resources''config''services.yml 中添加了

parameters:
    router.options.generator_base_class: Melofania'MainBundle'UrlGenerator

并创建了文件MainBundle''UrlGenerator.php

namespace Melofania'MainBundle;
use Symfony'Component'Routing'Generator'UrlGenerator as BaseUrlGenerator;
class UrlGenerator extends BaseUrlGenerator
{
    protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens)
    {
        $url = parent::doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens);
        return str_replace('%20', '+', $url);
    }
}

但是相反的程序还没有解决方案。我的意思是,带有加号的 URL => 控制器中带有空格的路由参数。我尝试使用UrlMatcher,但没有成功。如果您有答案,请写在此页面上:在Symfony 2中动态转换路由参数的值

我找到了一个解决方案,它对我有用。首先,我创建了一个服务来编码/解码 url。因此,您在控制器中str_replace('--the escape character--','+')(使用服务或其他替代方案),您将拥有如下所示的内容:

myRoute:
    path: /{argument}
    controller: sampleController

原始网址:

http://example.com/lorem+ipsum

所以在这里,你的sampleController会得到这样的$argument

$argument = 'lorem+ipsum';

在这里,您只需对其进行解码:

$theOriginal = str_replace('+','%20',$argument);

对于树枝,如果您需要显示它,您只需像这样添加过滤器"替换":

{{ app.request.attributes.get('_route_params')['argument']|replace('+',' --the escape character--')}}