Reputation: 49
I wrote small routing system, but I have problem with it. My regex is reading slash as a normal string and I've got confused how to make it working. For example:
I defined route home/[a-zA-Z0-9_]
that will show profile, but i defined also home/user/\d
. When I write down second case, home/user/45
, it will write down first case. It will take user/45
as one string. How I can exclude that /
using regex.
Upvotes: 1
Views: 5112
Reputation: 733
Since you are trusting the regex on this you really should limit the pattern. And also another trick to make patterns more readable is to use another pattern character:
|^/home/(\w+)/?$|
|^/home/user/(\d+)/?$|
Upvotes: 0
Reputation: 9860
Try one of these:
<?php
$path = '/home/user/45';
preg_match_all('/home\/(\w+)/', $path, $matches);
/* Would set $matches to Array:
(
[0] => Array
(
[0] => home/user
)
[1] => Array
(
[0] => user
)
)
*/
preg_match_all('/home\/(\w+)/(\d+)/', $path, $matches);
/* Would set $matches to Array:
(
[0] => Array
(
[0] => home/user/45
)
[1] => Array
(
[0] => user
)
[2] => Array
(
[0] => 45
)
)
?>
Upvotes: 0
Reputation: 6390
You should match the following pattern:
/home\/user\/(\\d+)/
And replace it with the following:
home/user$1
In the first regex, I used a delimiter: a slash. If a delimiter isn't required, remove the first and the last slash.
Upvotes: 0
Reputation: 2801
Have you tried something like this?
[^\/]+
Or better
[a-zA-Z0-9_]+[^\/]+
If you go to regexr.com and put your string ( home/user/45
) it will select only home,user,45
(excepting the slash /
)
Upvotes: 2