Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with regex to match any url but that of admin folder

I am stuck with something I know must be simple but been going round in circles for a while now.

I want to create a regular expression for use with a cms routing feature using php and preg_match that matches any URL that doesn't begin with the string 'admin/' as somedomain.com/admin/ will be the admin part of the cms.

I have tried so far

preg_match('#^([^admin])+(.+)$#', 'mens-books'))

which fails as the url string 'mens-books' I am looking for is a match against the letter m in the string 'admin' so it fails.

I have tried doing it like this also:

preg_match('#^([^admin$])+(.+)$#', 'mens-books'))

as a dollar symbolises the end of string but that didn't work either.

I then did this:

preg_match('#^[?!=admin]+(.+)$#', 'mens-books'))

which returned true but only I think because the ?!= in the regex now will match anything that is beginning with a, d, m, i or n.

Is anyone able to help with this please. I am open to any suggestions.

Thankyou.

Matt

like image 973
Matthew Fedak Avatar asked Jun 08 '11 21:06

Matthew Fedak


People also ask

What is the correct regular expression to match a URL?

@:%_\+~#= , to match the domain/sub domain name. In this solution query string parameters are also taken care. If you are not using RegEx , then from the expression replace \\ by \ .

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

How do I use regex to match?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What does (? I do in regex?

E.g. (? i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.


1 Answers

if (substr($url, 0, 6) !== 'admin/')
{
  echo 'Yippie';
}

But to answer the regex question. When you use square brackets, you're specifying a character class. That means [admin] matches a single character that is either an a, a d an m an i or an n. If you skip the brackets, you're matching a literal string. But, as my code proofs, it is not needed to use regex at all if you need to check if a string starts with a fixed substring.

like image 103
GolezTrol Avatar answered Sep 21 '22 16:09

GolezTrol