Php regex help

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
getmizanur
Forum Commoner
Posts: 71
Joined: Sun Sep 06, 2009 12:28 pm

Php regex help

Post by getmizanur »

elloo,

i had a php test today and had to find what was wrong with the following regex

preg_match('/^(?:ftp://)?([^/]+)@i');

my answer

preg_match('/^(?:ftp:\/\/)?([^/]+@/i');

can anyone tell me if i'm correct or not.

and just for understanding, can anyone explain to me what this means (?:ftp://)?([^/]+)

thanks in advance
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: Php regex help

Post by ridgerunner »

getmizanur wrote:elloo,

i had a php test today and had to find what was wrong with the following regex

preg_match('/^(?:ftp://)?([^/]+)@i');

my answer

preg_match('/^(?:ftp:\/\/)?([^/]+@/i');

can anyone tell me if i'm correct or not.

and just for understanding, can anyone explain to me what this means (?:ftp://)?([^/]+)

thanks in advance

I think the solution they were looking for was this (changing only the firsr regex delim char from / to @):

Code: Select all

preg_match('@^(?:ftp://)?([^/]+)@i');
Your solution was almost correct, but you forgot to escape the forward slash inside the character class (and I don't think they actually wanted to match the @ at-sign - it was supposed to be the regex delimiter).

As to what does '(?:ftp://)?([^/]+)' mean? Well, it means:

Optionally match the literal text 'ftp://' and then match one or more non-forward slash characters capturing them into group one.

This is pretty basic stuff. Check out http://www.regular-expressions.info/.
Post Reply