Regular Expressions are your friends. post

Posted on

Two and a half years ago, when I first dove into web development, I wasn't very familiar with regular expressions. They certainly didn't look regular to me, looked more like someone's keyboard exploded. Now, having figured out a thing or two about them, I came across the following lines:

       $pos = strpos ( $this->user->privs, 'del');
     if ($pos===FALSE)
     { // edit not found in string privs
           return FALSE;
     } else {
      // figure out where the string ends by looking for a comma, return that substring
         $next_comma = strpos( $this->user->privs, "," , $pos);
            if ($next_comma===FALSE) $next_comma=strlen($this->user->privs);
            $len = $next_comma-$pos;
          $epriv = substr ($this->user->privs, $pos, $len);
           return $epriv;

Which I was able to boil down into the following:

    if ( preg_match("/del_[a-z]+/", $privString, $match) )
    {
        return $match[0];
    } else {
        return false;
    }

Categories: Programming

Tags: Oscarm.org, Programming