phpregexcodeigniterpreg-replace

Change language directory in a URL string


I use Codeigniter to create a multilingual website and everything works fine, but when I try to use the "alternative languages helper" by Luis I've got a problem. This helper uses a regular expression to replace the current language with the new one:

$new_uri = preg_replace('/^'.$actual_lang.'/', $lang, $uri);

The problem is that I have a URL like this: http://www.example.com/en/language/english/ and I want to replace only the first "en" without changing the word "english". I tried to use the limit for preg_replace:

$new_uri = preg_replace('/^'.$actual_lang.'/', $lang, $uri, 1);

but this doesn't work for me. Any ideas?


Solution

  • You could do something like this:

    $regex = '#^'.preg_quote($actual_lang, '#').'(?=/|$)#';
    $new_uri = preg_replace($regex, $lang, $uri);
    

    The last capture pattern basically means "only match if the next character is a forward slash or the end of the string"...

    Edit:

    If the code you always want to replace is at the beginning of the path, you could always do:

    if (stripos($url, $actual_lang) !== false) {
        if (strpos($url, '://') !== false) {
            $path = parse_url($url, PHP_URL_PATH);
        } else {
            $path = $url;
        }
        list($language, $rest) = explode('/', $path, 2);
        if ($language == $actual_lang) {
            $url = str_replace($path, $lang . '/' . $rest, $url);
        }
    }
    

    It's a bit more code, but it should be fairly robust. You could always build a class to do this for you (by parsing, replacing and then rebuilding the URL)...