1

Probably a simple solution but I am a beginner. I am trying to remove empty parameters from below string using regular expression.

Example:

amount=&country_code=&currency=USD&price=&product_name=&service_id=082ca04e53fa0f0a53f283cf7e62cd&profile=&id=

Outcome would be:

currency=USD&service_id=082ca04e53fa0f0a53f283cf7e62cd

Thanks in advance!

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Read [this](https://stackoverflow.com/a/48445939/3110695) – FortyTwo Aug 27 '18 at 13:59
  • You could also parse the queryString, manipulate the array and create a query String again. Might be a safer solution. https://stackoverflow.com/questions/5397726/parse-query-string-into-an-array – Capricorn Aug 27 '18 at 14:05

3 Answers3

2

I managed to come up with the following regex based solution. The regex consists of an alternation, which is necessary to handle the edge cases of possibly the first and/or last query terms being empty.

$input = "amount=&country_code=&currency=USD&price=&product_name=&service_id=082ca04e53fa0f0a53f283cf7e62cd&profile=&id=";
$input = preg_replace("/(?<=&|^)[^=]+=(?:&|$)|(?:&|^)[^=]+=(?=&|$)/", "", $input);
echo $input;

currency=USD&service_id=082ca04e53fa0f0a53f283cf7e62cd

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0
$data="amount=&country_code=&currency=USD&price=&product_name=&service_id=082ca04e53fa0f0a53f283cf7e62cd&profile=&id=";

$data=explode('&',$data);


foreach($data as $row){
    if(substr($row, strpos($row, "=") + 1)){
        $filteredArray[]=$row;
    }
}

$data=implode('&',$filteredArray);

echo $data;

This will create a new array only with your filtered elements. On the first step an array of all your elements in the url is created. Through regex i check if there is any value after the '=' symbol. If there is i push the data to a new array which i convert to string in the last step with implode.

The output is : currency=USD&service_id=082ca04e53fa0f0a53f283cf7e62cd

pr1nc3
  • 8,108
  • 3
  • 23
  • 36
0
    $url = 'https://stackoverflow.com/questions?amount=&country_code=&currency=USD&price=&product_name=&service_id=082ca04e53fa0f0a53f283cf7e62cd&profile=&id=';
    parse_str(parse_url($url, PHP_URL_QUERY), $out); // not empty key-value result as array
    $link = null;
    foreach ($out as $key => $value) {
        if (!empty($value)) {
            $link .= "$key=$value&";
        }
    }
    $link = rtrim($link, '&'); // not empty key-value result as string
TsV
  • 629
  • 4
  • 7