views:

511

answers:

4

Hi all, I need a function to get only the empty href query parameter names so I can replace them later with values from another array. After hours of failing at regular expressions, here is what i resorted to:

/**
* getEmptyQueryParams(URL)
* Input: URL with href params
* Returns an array containing all empty href query parameters.
*/
function getEmptyQueryParams(URL)
{

    var params = new Array( );
    var non_empty_params = new Array( );
    var regex = /[\?&]([^=]+)=/g; // gets all query params
    var regex2 = /[\?&]([a-zA-Z_]+)=[\w]/g; // gets non empty query params 

    while( ( results = regex.exec( URL ) ) != null )
    {
     params.push( results[1] );
    }
    while( ( results = regex2.exec( URL ) ) != null )
    {
     non_empty_params.push( results[1] );
    }
    while(non_empty_params.length > 0)
    {
     for(y=0;y < params.length;y++)
     {
      if(params[y] == non_empty_params[0])
      {
       params.splice(y,1);
      }
     }
     non_empty_params.shift();
    }
    return params;
}

It works, but looks ugly as hell... Is there any better way to do it? Any help is appreciated.

A: 

I guess you could do that with one regex that would match empty and filled params.

var regex = /[\?&]([a-zA-Z_]+)=([\w]*)/g;

while( ( results = regex.exec( URL ) ) != null )
{
    if (results[2] == '')
        params.push( results[1] );
}

To be tested, of course.

ybo
A: 
$parsedUrl = parse_url($url);
$query = $parsedUrl['query'];
$params = array();
parse_str($query, $params);

$emptyParamNames = array();
foreach ($params as $k=>$v) {
    if ($v === "")
        $emptyParamNames[] = $k;
}

EDIT:

Heh... thought this was tagged PHP for some reason.

Well, maybe it benefits someone someday :)

Jaka Jančar
A: 
function get_url_params($url) {
    $out = array();
    $parse = parse_url($url, PHP_URL_QUERY);
    if($parse) {
        foreach(explode('&', $parse) as $param) {
            $elems = explode('=', $param, 2);
            $out[$elems[0]] = $elems[1];
        }
    }
    return $out;
}

function get_empty_url_params($url) {
    $out = array();
    foreach(get_url_params($url) as $key => $value)
        if(empty($value))
            $out[] = $key;
    return $out;
}
chaos
This is actually a Javascript question. But don't worry, you're not the only one to make the mistake :P
Jaka Jančar
D'oh. That's amusing.
chaos
+3  A: 

I just tested that this works in Opera and Chrom, the two browsers I have open right now:

function getEmptyQueryParams(URL)
{
    var params = new Array();
    var regex = /[\?&]([^=]+)=(?=$|&)/g; // gets non empty query params
    while( ( results = regex.exec( URL ) ) != null )
    {
        params.push( results[1] );
    }

    return params;
}
Jordan Miner