I'm building a route system and there's a need for URI segment
variables, that match exactly [A-Za-z]
It's very important to note, that a variable can be at any position (not only at the start or at the end),
For example, this could be
/post/(:letter)/comment/(:letter)
or
/user/(:letter)
or
/(:letter)
so that, I cannot rely on ^
and $
The problem is that, it doesn't work as expected ===
This matches both numbers and letters, which is undesirable. I care about letters and only.
I want this to be able to match only A-Za-z
, not digits and anything else, because an URI variable have to contain letters and only.
To demonstrate the problem in action,
$pattern = '~/post/(:letter)/commentid/(:letter)/replyid/(:letter)~';
$pattern = str_replace('(:letter)', '[A-Za-z]+', $pattern);
$uri = '/post/foo/commentid/someid/replyid/someanotherid';
preg_match($pattern, $uri, $matches);
print_r($matches); // Success
Now look at this:
$uri = '/post/foo123/commentid/someid123/replyid/someanotherid123';
preg_match($pattern, $uri, $matches);
print_r($matches); // Also success, I don't want this!
As you can see, this is undesireable because variables,
foo123
, someid123
, someanotherid123
contain numbers as well.
The question is,
$magic_regex = 'What should it be to match exactly [A-Za-z] at any position?';
$pattern = str_replace('(:letter)', $magic_regex, $pattern);