2

I am trying to validate following type of string using regular expressions in PHP. Using PHP 5.5.9.

String is in following format:

/[sometext]/course/[sometext1]/[sometext2]

What I need is a regex that will accept string that is only in that format and nothing else. Meaning these would be invalid:

/aaa/course/bbb/ccc/
/aaa/course/bbb/ccc/ddd

What I have so far is this:

/\/(?P<domain>.+?)\/course\/(?P<courseid>.+?)\/(?P<reportname>.+?)/

Any ideas?

Update:

With the help from all posters and especially wiktor-stribi%c5%bcew I got this one that works:

 $regex = '#^/(?P<domain>[^/]+)/course/(?P<courseid>[^/]+)/(?P<reportname>[^/]+)$#';
1
  • 1) Used negated character class, 2) Use anchors. Commented Feb 24, 2016 at 14:58

2 Answers 2

1

You can use the following regular expression:

^\/(?P<domain>[^\/]+)\/course\/(?P<courseid>[^\/]+)\/(?P<reportname>[^\/]+)$

PHP:

$re = '~^/(?P<domain>[^/]+)/course/(?P<courseid>[^/]+)/(?P<reportname>[^/]+)$~';

See the regex demo

The [^\/] is a negated character class that matches any character but /.

The ^ and $ are usually enough to make sure your input starts and ends with the current pattern (you can replace them with \A and \z respectively to make sure the \z matches at the very end of the string, or use ^/$ with the /D modifier).

Even if you use lazy .+? dot matching, the . can overflow several / delimiters if it is necessary to return a valid match.

Sign up to request clarification or add additional context in comments.

2 Comments

This looks promising. What about named group values? I would also prefer those.
I added them, sorry, was busy with another answer.
1

first... use something other than '/' as your delimiter (the slashes as the beginning and end of the regex)... it makes it easier to write the regex without having to escape the delimiter within

$regex = '#^/[a-z]+/[^/]+/[a-z]+/[a-z]+$#'

5 Comments

This regex will fail if there is a digit inside and matches strings without /course/.
@WiktorStribiżew yes... but is it supposed to match alphanumeric, numeric, alpha-only? anything sans "/"? nobody knows except the OP
OP can't know that either, that is why negated chwracter class is required here. See my answer for details.
@WiktorStribiżew cool... I used [^/] for the course segment... I infered from his examples that the other 3 segments were alpha-only
:-) Those are mere placeholders.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.