Answer the question
In order to leave comments, you need to log in
How to extract the desired value from the address bar from the url?
Hello!
Please tell me what's wrong?
There is a code with an array of cities, the purpose of which is to get the desired value from the link, compare it with the values in the array and, if it matches, replace it with another value:
// Примечание: изначально для определения ссылки в адресной строке использую REQUEST_URI
// $url = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$url = 'https://mysite.ru/uzlovaya/products';
$cities_list = [
// 'moscow'=> ['IP'=>'Москва', 'RP'=>'Москве'],
// 'novosibirsk'=>['IP'=>'Новосибирск', 'RP'=>'Новосибирске'],
// 'arhangelsk'=> ['IP'=>'Архангельск', 'RP'=>'Архангельске'],
// 'balahna'=> ['IP'=>'Балахна', 'RP'=>'Балахне'],
// 'uzlovaya'=> ['IP'=>'Узловая', 'RP'=>'Узловой'],
// 'rostov-na-donu'=> ['IP'=>'Ростов-на-Дону', 'RP'=>'Ростове-на-Дону'],
'uzlovaya'=>'Узловой'
];
$text = $url;
echo ( str_replace(array_keys($cities_list ), array_values($cities_list ), $text) );
$url = 'https://mysite.ru/uzlovaya/products';
, replaces "uzlovaya" with "Nodal", only doing it this way: https://mysite.ru/Узловой/products
'uzlovaya'=> ['IP'=>'Узловая', 'RP'=>'Узловой'],
Answer the question
In order to leave comments, you need to log in
Understood.
1. Determined the url in the address bar
2. Split the url into an array and removed from the values - "/"
3. Determined the number of the key that corresponds to the value of the city - $city_name[2];
( [2] - means that the value I need is the second in a row)
4. Using str_replace from the $custom_cities array, I replaced the received value with the required one and displayed it on the page.
$url = $_SERVER['REQUEST_URI'];
$city_name = explode("/", $url);
$custom_cities = [
// массив городов может быть и 100 и 200 городов и более
'domodedovo' => 'Домодедово',
'uzlovaya' => 'Узловой',
'rostov-na-donu' => 'Ростове-на-Дону'
];
$text = $city_name[2];
echo ( str_replace(array_keys($custom_cities), array_values($custom_cities), $text) );
}
lmgtfy.com/?q=php+routing
Specific examples:
Symfony Routing (see "placeholders")
PhpLeague Route (see "Wildcard Routes")
Aura.Router
In your case, a route like this should be defined: /{city_name}/products
(this is an example of Symfony Routing , in others, the meaning will not be radically different)
Further, if a request hits this route, you pass data to the desired controller - in this case, the value of the parameter city_name
, and the logic associated with processing different cities is already working there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question