Problems with regular expressions (friendly url)

Asked

Viewed 400 times

7

I’m having trouble reading the code of a particular product from a friendly URL.

With the regular expression I put, it is accepting all the characters that are in front of the product code, ie writing produto/9789/quantidade/5 he understands the product code as 9789/quantidade/5, and not only the 9789.

Could someone help me put that regular expression correctly?

Here’s the one I used:

RewriteRule ^carrinho\/produto\/(.+)?$ carrinho.php?produto=$1&quantidade=1 [NC,L]
RewriteRule ^carrinho\/produto\/(.+)\/quantidade\/([0-9]+)\/?$ carrinho.php?produto=$1&quantidade=$2 [NC,L]

Another problem is that when the user places a / at the end of the product code in the first URL it goes together to the product code.

3 answers

2

^carrinho\/produto\/(.+)?$

Means capturing carrinho/produto/ optionally followed by anything to the end of the line. That’s the problem anything. By the rule, it may well be 9789/quantidade/5.

Rewrite limiting to be just numbers. So:

^carrinho\/produto\/(\d+)?$

Or if you prefer:

^carrinho\/produto\/([0-9]+)?$
  • The problem is that the product will not necessarily only have numbers, it can be composed of letters and special characters... How should I make the mask for this case?

2

The first expression can be adjusted to not capture / in the product:

^carrinho\/produto\/([^\/]+)?$

So it won’t hit with the long Urls that have amount, leaving them for the second expression, which seems to be working fine.

1

I don’t know if it’s useful to you, but here is an expression to search only the parameters passed from the url, I didn’t run tests with multiple urls just the one you passed.

Regex

(\w+=([^&]*))

Explanation

\w+= = alnum - letras a números - 1 ou mais - seguido de =
[^&]* = tudo exito & - se quiser limitar para `alnum` substiruir por [\w]*, - 0 ou mais

Amendments

This Regex will return you an array as you can see here.

Caso queira um array simples de `tipo=dado` elimine o parenteses interno (\w+=[^&]*)
Caso queira um array de `dados` elimine o parenteses externo \w+=([^&]*)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.