Php 用Symfony2中URL中的加号替换空格
如果我在Symfony2中生成带有空格的URL,例如:Php 用Symfony2中URL中的加号替换空格,php,symfony,url,Php,Symfony,Url,如果我在Symfony2中生成带有空格的URL,例如: example.com/some text 然后此URL显示在站点上,如: example.com/some%20text 如何设置以加号替换空格,而不是以%20替换 在这种情况下: example.com/some+text 我需要通用解决方案,而不是在所有URL中添加|替换“%20”和“+”。谢谢大家的回答,我找到了自己的解决方案 在MainBundle\Resources\config\services.yml中添加了 para
example.com/some text
然后此URL显示在站点上,如:
example.com/some%20text
如何设置以加号替换空格,而不是以%20替换
在这种情况下:
example.com/some+text
我需要通用解决方案,而不是在所有URL中添加|替换“%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与pluses=>路由参数与控制器中的空格。我尝试使用UrlMatcher,但没有成功。如果你有答案,请写在这页上:
我找到了一个解决方案,它对我很有效。首先,我创建了一个对url进行编码/解码的服务。因此,使用服务或其他替代方案在控制器中str_替换“-转义字符-”、“+”,您将得到如下结果:
myRoute:
path: /{argument}
controller: sampleController
$argument = 'lorem+ipsum';
原始url:
http://example.com/lorem+ipsum
因此,您的sampleController将获得如下$argument:
myRoute:
path: /{argument}
controller: sampleController
$argument = 'lorem+ipsum';
在这里,您只需解码它:
$theOriginal = str_replace('+','%20',$argument);
对于twig,如果需要显示它,只需像这样添加过滤器替换:
{{ app.request.attributes.get('_route_params')['argument']|replace('+',' --the escape character--')}}
你的url是用db内容中的一些“slug”构建的吗?如果是,则应使用slugify。实现此功能的捆绑包:在堆栈溢出时,不需要使用HTML来格式化代码示例。根据我的编辑,只需确保您的代码前后都有换行符。为url创建自定义字段类型?您可以创建一个自定义细枝函数,例如path_plus,它将字符串从空格转换为+并由此生成url。