1

I can't get this function working correctly:

function isValidURL($url){
 return preg_match('%http://domain\.com/([A-Za-z0-9.-_]+)/([A-Za-z0-9.-_]+)%', $url);
}

The url:

http://domain.com/anything-12/anything-12/

can contain numbers, letters and symbols _ -

I assume its to do with the first regex - as these work

    http://domain.com/anything12/anything12/

    http://domain.com/anything12/anything-12/

    http://domain.com/anything12/any-thing-12/

    http://domain.com/anything_12/any-thing-12/

As always all help is appreciated and thanks in advance.

2
  • If you want to validate a url why not use filter_var ($url, FILTER_VALIDATE_URL) instead of a regex? Or parse_url(). Just curious. Commented Nov 15, 2011 at 6:40
  • It needs to match a single domain not any. Commented Nov 15, 2011 at 7:11

1 Answer 1

5
  1. You need to escape the - in the character class of your regex.

  2. You need to anchor your regex so that tries to match the entire input string and not part of it.

The modified regex is:

'%^http://domain\.com/([A-Za-z0-9.\-_]+)/([A-Za-z0-9.\-_]+)/$%'

You can shorten your regex by noting that [A-Za-z0-9_] is same as \w and also there is a repeating sub-regex.

'%^http://domain\.com(/[\w.-]+){2}/$%'
Sign up to request clarification or add additional context in comments.

2 Comments

I think it has to be (/[\w.-]+){2} because OP seems to need both the sub-expressions.
Hmmm it dosen't seem to be working in Google chrome or Safari ...any ideas? (works fine in FF and IE)

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.