Regex to check for a number in the url using Twig

This wouldnt be a big problem if I had known Twig a little more. Here is my code, I am trying to check whether the url contains number in it.

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

none of these work

thanks in advance

5

2 Answers

See Twig reference:

For complex string comparisons, the matches operator allows you to use regular expressions:

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

So, to check if a string contains a digit with a regex, just use

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

Why using Twig for this ? should be more reliable to use the routing functionnalities ?

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

here {id} has to be a integer ( with \d+ rules ) otherwise an exception will be triggered.

easier , no ?

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like