Search code examples
phppreg-match

i want to match exactly contact-us page but not working


i want to match contact-us page exactly present in the url

the combination could be..

contact.*        i,e(extension could be .html or .php or .aspx)
contact-us.*     i,e(extension could be .html or .php or .aspx)
contact.*        i,e(extension could be .html or .php or .aspx)
contactUs.*      i,e(extension could be .html or .php or .aspx)

without extension

contact        i,e(no extension)
contact-us    i,e(no extension)
contact       i,e(no extension)
contactUs     i,e(no extension)

right now i'm using this code which matches everything

$page = "http://www.example.com/contact-usmsdnds";
if(preg_match('/contact|contact-us|contact-us(.php|html)|contact(.php|html)/siU',$page)){
    echo "Matched";
 }else{
   echo "No Match";
}

here is a demo : http://phpio.net/s/1i2p

i'm ready to accept solution with totally different code

please help me thanks in advance!!


Solution

  • You may use

    '~/contact(?-i:-us|Us)?(?:\.(?:aspx|php|html))?/?$~i'
    

    See the regex demo

    It matches:

    • /contact - a substring /contact
    • (?:-us|Us)? - an optional substring -us or Us
    • (?:\.(?:aspx|php|html))? - an optional sequence of a . + any of the alternatives substrings ()
    • /? - an optional /
    • $ - end of string.

    Note that (?-i:...) is a modifier group where the alternatives are matched in a case insensitive way (the general /i modifier at the end does not affect this group).