$re = '/(?:\/[a-z]{2})?\/[a-z]{2}[-_][a-z]{2}\b|\/(retail)\/[a-z]{2}\b/m';
$str = '/us/en_us/retail/en (matches /us/ and /us/en_us/)
/us/en_us/retail (matches /us/ and /en_us/)
/gb/en_gb/retail/en-uk (matches /en_gb and /en-uk)
/us/en_us/retail/en
/us/en_us/retail
/gb/en_gb/retail/en-uk/
/us/en_us/e/retail/Ctral/Apps/jcr:content/par/expandableciner_57473905/image/file.img.png/1496964235.png
/gb/retail/cowabunga
/gb/en_gb/retail/en-uk
/gb/en_gb/retail/en-uk/blah
/de/de_de/retail/de_de/products/catalog
/en-en/ab/cd';
$subst = "$1";
$result = preg_replace($re, $subst, $str);
echo "The result of the substitution is ".$result;
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php