简体   繁体   中英

PHP to replace 2 character at nth position in an string

I am developing bilingual website in codeignitor and i have created language files. All works fine except when switching the language i want to replace the language abbraviation in the url at 31th and 32th position starting at 0.

English Url :

$url=http://localhost/abc/index.php/ en /news/title/new-version-of-goldendict-with-dzongkha

Dzongkha Url :

$url=http://localhost/abc/index.php/ dz /news/title/new-version-of-goldendict-with-dzongkha

i just want php to change en to dz

i tried

$url=http://localhost/abc/index.php/ en /news/title/new-version-of-goldendict-with-dzongkha

$lang_id='dz';

$old_lang=substr($url, 31, 2);

$newurl = str_replace($old_lang,$lang_id,$url );

However above codes changes dz to en but also replaces 45 and 46 character. This is what happens after conversion.

$url=http://localhost/abc/index.php/ dz /news/title/ dz w-version-of-goldendict-with-dzongkha

Any one who has an idea whats happening

Since you are implying that the country code is always at the 31th position in your string, you can use the substr_replace function to limit the scope of your replacement.

$newurl = substr_replace($old_lang, $lang_id, $url, 31, 2);

Another option is to be more specific in your search string as proposed by Scuzzy in the comments : $newurl = str_replace('/en/','/dz/',$url);

Try this -

$url="http://localhost/abc/index.php/en/news/title/new-version-of-goldendict-with-dzongkha";

echo $str = substr_replace($url,'dz',31,2);

Hope this will help you.

<?php

$url = "http://localhost/abc/index.php/en/news/title/new-version-of-goldendict-with-dzongkha";

function changeLanguage($url, $language)
{
    $new_url = "";
    $url_broken = explode("/", $url);
    foreach ($url_broken as $key => $value) {
        if (strpos($value, ".php")!==false) {
            $lang_index = $key+1;
            break;
        }
    }
    if (isset($lang_index)) {
        $url_broken[$lang_index] = $language;
    }
    $new_url = implode("/", $url_broken);
    return $new_url;
}

$url = changeLanguage($url, "dz");
var_dump($url);

This method will help you to change the language on the basis of pattern not on the basis of position. And of course in this i have considered language will be after *.php/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM