0

How to remove multiple redundant query string from url?

Hence, like below string,

Url:

localhost.com/en_ar/body?products_type=235&treatment=132?product_type=235&treatment=132&__from_store=en_bh

Resultant Url:

localhost.com/en_ar/body?product_type=235&treatment=132&__from_store=en_bh

How to remove first portion of content from string between ?content? if exist in querystring using php.

In our case remove content ?products_type=235&treatment=132? from string.

2 Answers 2

2

You ca use the following regex(DEMO):

(\?(?<=\?).*(?=\?))

It will look around for ? and match all content between 2 ?, along with the 1st ?.

And the following PHP Code(DEMO):

$str = "localhost.com/en_ar/body?products_type=235&treatment=132?product_type=235&treatment=132&__from_store=en_bh";
$newStr = preg_replace('/(\?(?<=\?).*(?=\?))/', '', $str);
var_dump($newStr);
Sign up to request clarification or add additional context in comments.

Comments

1

Whether you have 1, 2, or more "sets of querystrings" in your url, my pattern/method will match/consume all of them but only capture the last. For this reason, there will only actually be 1 replacement performed, and the replacement text will be the captured substring ($1).

Code: (Demo)

$url='localhost.com/en_ar/body?abcd?products_type=235&treatment=1‌​32?product_type=235&‌​treatment=132&__from‌​_store=en_bh';

echo preg_replace('/(\?[^?]*)+/','$1',$url);

Output:

localhost.com/en_ar/body?product_type=235&‌​treatment=132&__from‌​_store=en_bh

Pattern Explanation: (Just 14 steps: Demo)

/        // pattern delimiter
(        // start capture group
  \?     // match a question mark
  [^?]*  // greedily match zero or more non-question marks
)+       // end capture group -- repeat one or more times
/        // pattern delimiter

3 Comments

$url = "localhost.com/en_ar/body?abcd?products_type=235&treatment=132?product_type=235&treatment=132&__from_store=en_bh"; echo preg_replace('/\?[^?]*/','',$url,1);
output will be like, localhost.com/en_ar/body?product_type=235&treatment=132&__from_store=en_bh means all query string except last will be purged.
I have made a final edit to my answer. I have removed the old patterns and left only the best one for your task. If you have questions, please ask.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.