user2177129
user2177129

Reputation:

simple regex to validate url returns always false with preg_match

I know there are a lot topics out there which show Regular Expressions to validate URL's. Also there is a FILTER_VALIDATE_URL function out there, i do know that too.

I'd like to know whats wrong with my regular expression to understand whats wrong with it.

My RegularExpression should match URL's with http:// or https:// in front of it. After that it can be any character, one or more. It should end with a dot and after that a string with 2 to 5 characters a-z.

        $s = preg_match('^(http|https)://.+(\.[a-z]{2,5})$', $url);

I tried this RegularExpression on http://regexpal.com/. It matches correctly, but my preg_match call gives me always false. Can anyone explain to me whats incorrect about this RegularExpression?

Thank You Very Much

Upvotes: 0

Views: 1988

Answers (1)

Andy E
Andy E

Reputation: 344675

In PHP, you're required to use delimiters in your regular expression syntax. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. Most people use / as a delimiter, but since this appears in your URL you can use another character, such as # to avoid escaping:

'#^(http|https)://.+(\.[a-z]{2,5})$#'

Side note: (http|https) will capture as it is wrapped in parenthesis. You don't really need this, but it's also simpler to just write https?, where the ? makes the s an optional character in the expression.

Upvotes: 3

Related Questions