0
<?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

?>

问:如何从字符串中删除所有参数(&lang=en,&lang=sk)?

先感谢您

4

3 回答 3

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
于 2013-08-11T18:52:43.470 回答
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);
于 2013-08-11T18:55:30.560 回答
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

于 2013-08-11T18:58:41.767 回答