我有获取网址的变量。然后从该URL中删除另一个URL。第一个网址会删除另一个网址,但第二个网址不是,因为它包含俄语单词。如何从网址中删除俄语字母:
$url = $_SERVER['REQUEST_URI'];
$url2 = $_SERVER['REQUEST_URI'];
if (isset($_GET['page'])) {
page = $_GET['page'];
}
if (isset($_GET['category'])) {
$category = $_GET['category'];
}
$url = str_replace('&page='.$page, "", $url); // works
$url2 = str_replace('&category='.$category, "", $url2); // does not working
echo $url2; // i check and $url2 does not remove category, because it contains Russians words
答案 0 :(得分:0)
尝试使用str_replace()
上的urlencode搜索字符串的出现,如下所示:
$url2 = str_replace('&category='. urlencode($category), "", $url2);
让我知道这是否有帮助。
答案 1 :(得分:0)
借助您环境中的http_build_query(或其polyfill),您可以编写一个简单的函数来即时重写查询参数,而无需使用str_replace。
例如,要重写“类别”参数,您可以
<?php
function uri_rewrite_query($uri, $callback) {
$parsed = parse_url($uri);
parse_str($parsed['query'] ?? '', $query);
$parsed['query'] = http_build_query($callback($query));
return http_build_url($uri, $parsed);
}
function query_remove_category($query) {
unset($query['category']);
return $query;
}
function query_replace_category($category) {
return function ($query) use ($category) {
$query['category'] = $category;
return $query;
};
}
然后您可以执行以下操作:
<?php
$uri = '/beverages.php?lang=ru&category=some_category';
echo uri_rewrite_query($uri, 'remove_category');
// Result: /beverages.php?lang=ru
echo uri_rewrite_query($uri, query_replace_category('Безалкогольные напитки'));
// Result: /beverages.php?lang=ru&category=%D0%91%D0%B5%D0%B7%D0%B0%D0%BB%D0%BA%D0%BE%D0%B3%D0%BE%D0%BB%D1%8C%D0%BD%D1%8B%D0%B5+%D0%BD%D0%B0%D0%BF%D0%B8%D1%82%D0%BA%D0%B8 (equivalant to "/beverages.php?lang=ru&category=Безалкогольные напитки")
或者如果您仅对查询字符串感兴趣:
function uri_get_query() {
$parsed = parse_url($uri);
parse_str($parsed['query'] ?? '', $query);
return $query;
}
echo '/food.php?' . http_build_query(query_remove_category($_SERVER['QUERY_STRING'] ?? ''));
echo '/food.php?' . http_build_query(query_replace_category('Безалкогольные напитки')($_SERVER['QUERY_STRING'] ?? ''));