Regex使用Twig在url中检查数字


Regex to check for a number in the url using Twig

如果我对Twig有更多的了解,这不会是什么大问题。这是我的代码,我正在尝试检查url中是否包含数字。

{% set x = req.path %}
{% set matches = x|regex_match('~['d'.]+$~') %}
{% set matches = x|regex_match('~[0-9]*$+~') %}

这些都不起作用

提前感谢

参见Twig参考:

对于复杂的字符串比较,matches运算符允许您使用正则表达式:

{% if phone matches '/^[''d''.]+$/' %}
{% endif %}

因此,要检查字符串是否包含带有正则表达式的数字,只需使用

{% if x matches '/''d/' %}
    Do Stuff
{% endif %}

为什么要使用Twig?应该更可靠地使用路由功能吗?

my_route_to_check:
pattern:  /my/route/{id}
defaults: { _controller: acmeMybundle:myController:myAction, id:0}
requirements:
     id : 'd+

这里{id}必须是一个整数(带有''d+规则),否则将触发异常。

更容易,不是吗?