Fresh Blurbs Tag Filtering in PHP/Drupal

Filtering content through URI tagging was initially popularized by and is now a common way to quickly navigate content. For instance, in a system that supports this type of navigation, you can constract a URL:\,rss

and get a vertical view of the domain data. In this markup, "+" stands for logical AND, whereas "," stands for logical OR.

Following is a PHP code snippet that processes "delicioused" query string into a logical expression (you can modify the code slightly and get an SQL where clause instead). In addition to the original syntax, it allows tags with spaces in them. You just need to enclose those in single or double quotation marks. For instance, the following expression is a valid one:,rss,'Steve Jobs'. Note: using quotation marks inside the tag names is still invalid syntax!

And following is the code sample:

//Node: URL processor converts "+"s in the URL into spaces " ", so we are taking
//additional steps to distinguish the two post-factum. Namely, you need to enclose
//all spaces-containing tags in quotation marks

function parseargs ( $reqstr ) {

  //escape the spaces in tags inside quotation marks:
  $pattern  = '/\'.*?\'/';
  $reqstr  = preg_replace_callback ($pattern,"replacementcallback",$reqstr);
  $pattern  = '/".*?"/';
  $reqstr  = preg_replace_callback ($pattern,"replacementcallback",$reqstr);

  //replace the rest of the spaces with plus signs
  $reqstr = preg_replace ( '/\s+/', '+', $reqstr);
  //remove quotation marks
  $reqstr = preg_replace ( array('/"/', '/\'/'), '', $reqstr );                           

  //split into tags and corresponding operands: + and ,
  $arguments = preg_split( '/([,+])/',$reqstr,-1,PREG_SPLIT_DELIM_CAPTURE );

  //You can modify the code from here if you need to generate an
  //SQL Where clause instead.  

  $rejoined = implode(" ",$arguments);

  $rejoined =  preg_replace ( array( '/\+/', '/,/'), array('AND','OR'), $rejoined);
  $rejoined = urldecode ( $rejoined );

 // echo "

  return $rejoined;

// in parseargs, we need to replace spaces
// in all quote-enclosed substrings with "%20s". The
// only practical way of doing that is with preg_replace_callback
function replacementcallback ( $match ) {

  $input = $match[0]; // For our case, it's always one match.
  $ret =  preg_replace('/\s+?/', '%20', $input );
  return $ret;                                 


comments powered by Disqus