Multiple regular expressions in a string with bars

6

I need a regular expression that matches the end of a URL in the following format:

/somente-letras/somente-numeros[/]

To combine the part of somente-letras , I used ~^/[A-Z]+$~ , however from the moment I put a bar, nothing else works.

The tests I did:

URL: /testando-minha-url
REGEX: ~^/[a-z-]+$~
SAÍDA: true

Placing a slash at the end of the URL

URL: /testando-minha-url/
REGEX: ~^/[a-z-]+$~
SAÍDA: false

Placing a slash in the expression

URL: /testando-minha-url/
REGEX: ~^/[a-z-]/+$~
SAÍDA: false

That is, my problem is from the forward slash.

Then after the toolbar, I need to match only numbers, and possibly which endbar is optional, work with or without it.

I'm using the preg_math function of PHP, preg_match($regex, $str)

Is it possible? Where am I going wrong?

    
asked by anonymous 16.12.2015 / 17:28

2 answers

5

The following expression solves my problem: ^\/[a-z\-]+\/[0-9]+\/?+$

I found the solution using this site that was suggested through Sergio together with a little apprenticeship at RegexOne

I saved the solution on the link that can be tested: link

    
16.12.2015 / 18:27
4

Your mistake was to put + in the wrong place:

URL: /testando-minha-url/
REGEX: ~^/[a-z-]/+$~
SAÍDA: false

This is telling you to marry a slash, then a single character that is either letters or dashes, followed by one or more slashes. Putting + in the right place should solve your problem:

URL: /testando-minha-url/
REGEX: ~^/[a-z-]+/$~

This houses a slash, followed by one or more characters that are letters or dashes, followed by a slash at the end.

From there, just do the same thing for the numbers, putting a ? on the last bar to make it optional ( as you have already discovered ):

~^/[a-z-]+/\d+/?$~
    
17.12.2015 / 03:42