skip to Main Content

I want to pick up the ISO code (two letters) of a country using a REGEX expression

For example, for the country Ireland the ISO code is ie. The ISO code could be found after the slash / or after the last .

This is my RewriteRule:

RewriteRule ^gallery/country(?:/[^/]*([a-zA-Z-9]{2}))?/?$ gallery/gallery.php?country=$1 [L,QSA]

Here are some valid url’s… If available, I want to pick the ISO Code:

gallery/country

gallery/country/

gallery/country/ie

gallery/country/ie/

gallery/country/ireland

gallery/country/ireland/

gallery/country/ireland-love.ie

gallery/country/ireland-love.ie/

gallery/country/ireland.69-love.ie/

I’ve try to adapt the template formula that I use pretty much for all of my seo url’s, but i’m having difficulties with this one. Here’s what I’ve done so far.

^gallery/country(?:/[^/]*([a-zA-Z-9]{2}))?/?$

https://regex101.com/r/88azeh/6

2

Answers


  1. Could you please try following, based on your shown samples. Catching everything after . in a reference group and using it while rewriting here. Please make sure you clear your browser cache before testing any URLs.

    RewriteEngine ON
    RewriteCond %{QUERY_STRING} ^$
    RewriteRule .([a-zA-Z]+){2}/?$ gallery/gallery.php?country=$1 [L]
    


    Above will not check about URI’s condition, to make it more specific to gallery only try following.

    RewriteEngine ON
    RewriteCond %{QUERY_STRING} ^$
    RewriteRule ^gallery/country.*.([a-zA-Z]+){2}/?$ gallery/gallery.php?country=$1 [L]
    
    Login or Signup to reply.
  2. You can use

    ^gallery/country/(?:.*[/.])?([a-zA-Z]{2})/?$
    

    See the regex demo. Details:

    • ^ – start of input
    • gallery/country/ – a literal string
    • (?:.*[/.])? – an optional pattern matching
      • .* – any zero or more chars other than line break chars as many as possible
      • [/.] – a / or .
    • ([a-zA-Z]{2}) – Group 1: two ASCII letters
    • /? – an optional /
    • $ – end of string.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search