Reputation: 27
using if else statement, I would like php to check if the first folder in the url is (en), example: http://www.domain.com/en/newyork/car/ if the first folder is [ en ] as shown above in the example, then I would like to change the ahref of a link that I have on the page
change link from: En
change link to: Ru
Looking at the example above, the only thing I want php to change is en or ru but keeps the remaining url of the current page as is
: if the current page url is http://www.domain.com/en/newyork/car/ the link would be Russian
Upvotes: 0
Views: 393
Reputation: 1929
In order to get the current language of your page, you will first have to get the path of your current URL, and then get the string after the first slash. You could do this as follows:
// Get the current URL
$current_url = $_SERVER['REQUEST_URI'];
// Get the 'path' portion (without things like 'http')
$url = parse_url($current_url);
// Split the String in an array
$parts = explode('/', $url['path']);
$lang = $parts[1];
$prepath = $url['scheme'] . '://' . $url['host'] . $parts[0];
// Array slice to get all remaining parts
$postpath = array_slice($parts, 2);
// Append the first part of your path, the new language, and finally
// the remainder of your URL.
$newurl = $prepath . '/' . ($lang == 'ru'?'':'ru/') . implode('/', $postpath);
After this, you can use an anchor on your page to allow the user to change:
<a href="<?php echo $newurl;?>">Change Language</a>
Upvotes: 1
Reputation: 109
function changeUrlComponent($url, $componentPos, $newVal) {
$url = parse_url($url);
$arr = explode('/',$url['path']);
$arr[$componentPos] = $newVal;
$url['path'] = implode('/',$arr);
return $url['scheme'] .'://'. $url['host'] . $url['path'];
}
echo changeUrlComponent('http://www.domain.com/en/newyork/car/', 1, 'ru');
Hope this helps. Also note you can add more to the returned value based on the expected no of url components. Refer to this. Also the componentPos should start from 1 to length of your directories/path. This would be a more generic approach than the ones answered above as they are too coupled with the expectation of a lang being present in the url.
Upvotes: 0
Reputation: 1007
<?php
$url = 'www.domain.com/en/newyork/car/';
$url_arr = explode("/en/", $url);
$new_url = implode("/ru/", $url_arr);
?>
Upvotes: 2