Gromstone
Gromstone

Reputation: 43

Link Shortner using preg_match

My code is:

if (!preg_match('^http(s)?://(*)?\.mysite.com(\*)^', $url))
{
  echo "<strong>Error</strong>: Invalid mysite.com link or could shorten link";
} 

and I got:

Warning: preg_match() [function.preg-match]: 
  Compilation failed: nothing to repeat at offset 12

I am working on a link shortner, similar to bit.ly, but I only want it to shorten links from my specific site.

I need some help with this error.

Upvotes: 1

Views: 234

Answers (2)

codaddict
codaddict

Reputation: 455132

The problem is here:

if (!preg_match('^http(s)?://(*)?\.mysite.com(\*)^', $url))
                              ^

You have used the * quantifier but you've not specified to what should this quantifier be applied to. You probably wanted .* there in place of just *.

Upvotes: 5

Ωmega
Ωmega

Reputation: 43673

The asterisk or star tells the engine to attempt to match the preceding token zero or more times.

if (!preg_match('^http(s)?://(*)?\.mysite.com(\*)^', $url))
                              ↑
                       nothing to match

I believe your regex pattern contains multiple errors. I suggest you to go with

if (!preg_match('/^https?:\/\/(?:[a-z\d-]+\.)*mysite.com(?:(?=\/)|$)/i', $url))

Upvotes: 5

Related Questions