foreach循环中的str_replace

时间:2013-08-11 18:48:31

标签: php foreach str-replace

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

提前谢谢

3 个答案:

答案 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)