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

?>

Q: How to delete all parameters (&lang=en, &lang=sk) from string ?

Thank you in advance

2
  • 1
    You are looking for parse_url, possibly with http_build_url, or it's PHP-code equivalent. Commented Aug 11, 2013 at 18:50
  • Why don't you have a valid querystring? Do you realize the key collisions? Will your real scenario always require the full destruction of the entire quasi-querystring? I don't see this being a clear, representative, and/or sufficiently challenging. Commented Aug 14, 2024 at 4:15

3 Answers 3

2

What you are doing is creating a new variable $new each time so that won't do anything good with the $url. Try to assign the str_replace back to its original variable like:

$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
Sign up to request clarification or add additional context in comments.

Comments

0

You want to use parse_url() http://www.php.net/manual/en/function.parse-url.php and then http_build_query() http://php.net/manual/en/function.http-build-query.php

1 Comment

Have you tried to implement this advice with the sample key collisions? Notice there is no leading ? for the querystring.
0

An Alternative:

First:

$url = "http://localhost/news&lang=en&lang=sk&lang=sk&lang=sk&lang=en";
echo preg_replace("#&lang=(en|sk)#", "", $url);

Second:

$url = "http://localhost/news&lang=en&lang=sk&lang=sk&lang=sk&lang=en";
echo str_replace(array("&lang=en", "&lang=sk"), "", $url);

Update: for long array of $lang:

$url = "http://localhost/news&lang=en&lang=sk&lang=sk&lang=sk&lang=en";
echo preg_replace("#&lang=(".implode("|", $lang).")#", "", $url);

1 Comment

array $langs can contain more values

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.