<?php
$url = "http://localhost/news&lang=en&lang=sk&lang=sk&lang=sk&lang=en";
$langs = array ('sk', 'en');
foreach ($langs as $lang) {
$search = '&lang='.$lang;
$new = str_replace($search, "", $url);
}
echo $new; // output: http://localhost/news
?>
问:如何从字符串中删除所有参数(&amp; lang = en,&amp; lang = sk)?
提前谢谢
答案 0 :(得分:2)
您正在做的是每次都创建一个新变量$new
,这样就不会对$url
做任何好事。
尝试将str_replace
分配回其原始变量,如:
$url = "http://localhost/news&lang=en&lang=sk&lang=sk&lang=sk&lang=en";
$langs = array ('sk', 'en');
foreach ($langs as $lang) {
$search = '&lang='.$lang;
$url = str_replace($search, "", $url);
}
echo $url; // output: http://localhost/news
答案 1 :(得分:0)
替代方案:
首先:
$url = "http://localhost/news&lang=en&lang=sk&lang=sk&lang=sk&lang=en";
echo preg_replace("#&lang=(en|sk)#", "", $url);
第二
$url = "http://localhost/news&lang=en&lang=sk&lang=sk&lang=sk&lang=en";
echo str_replace(array("&lang=en", "&lang=sk"), "", $url);
更新:适用于$ lang的长数组:
$url = "http://localhost/news&lang=en&lang=sk&lang=sk&lang=sk&lang=en";
echo preg_replace("#&lang=(".implode("|", $lang).")#", "", $url);
答案 2 :(得分:0)
您想使用parse_url()http://www.php.net/manual/en/function.parse-url.php然后使用http_build_query()http://php.net/manual/en/function.http-build-query.php