Hariis Basiic
Hariis Basiic

Reputation: 49

Regex - everything except slash

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

Answers (5)

Niko Hujanen
Niko Hujanen

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

WWW
WWW

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

ProgramFOX
ProgramFOX

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

Ionel Lupu
Ionel Lupu

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

Mkdgs
Mkdgs

Reputation: 177

try home/(?!user/)[a-zA-Z0-9_] for first case

Upvotes: 0

Related Questions