Location: PHPKode > scripts > Regexp store > regexp_store.class.php
<?
/**
* Class regexp_store version 1
* @regular expresions store in MySQL.
* @author Uldis Nelsons
* @version 1.0
* Created at 2009.09.01
*/

class regexp_store
{
	public $aTable = array();

/*
*  get all regular expresions in array
*  Params:
*  $sTableName - patterns table name. Default is regexp_store
*/
	public function __construct($sTableName = 'regexp_store')
	{
	    //load from MySQL data
        $sql = "
            select
                group_name,
                name,
                pattern,
                replacement,
                begin_end_symbol
            from
                ".$sTableName."
            where
                deleted = 0
            order by
                group_name,sqn
            ";
        $res = mysql_query($sql);
        if (mysql_num_rows($res) > 0)
        {
            while($aRow = mysql_fetch_assoc($res))
            {
                if (empty($this->aTable[$aRow['group_name']]))
                  $this->aTable[$aRow['group_name']] = array(
                                                    'pattern'   => array(),
                                                    'replace'   => array(),
                                                    );

                $this->aTable[$aRow['group_name']]['pattern']  [$aRow['name']] = $aRow['pattern'];
                $this->aTable[$aRow['group_name']]['replace']  [$aRow['name']] = $aRow['replacement'];
                $this->aTable[$aRow['group_name']]['d']        [$aRow['name']] = $aRow['begin_end_symbol'];
            }
        }
	}

    /*-----------------------------------------------------------------------------\
    |                           public functions                                   |
    \-----------------------------------------------------------------------------*/

    /**
     * METHOD: preg_replace
     * work identical php preg_replace.
     * params:
     * $sGroup - regular expresion group name defined in table in field group_name
     * $sName - regular expresion name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * $Data -  The string or an array with strings to search and replace
     * return:
     *  returns an array if the subject parameter is an array, or a string otherwise.
     *  if error ocured, return same $Data and triger error
     */

    public function preg_replace ($sGroup,$sName,$Data)
	{
        $aP = $this->GetRegexpPatern($sGroup,$sName);
        $aR = $this->GetReplacement($sGroup,$sName);
        if ($this->suspend_bad_regexp_pattern($aP, $aR))
            return preg_replace($aP, $aR, $Data);
        else
            return $Data;
	}

    /**
     * METHOD: str_replace
     * work identical php str_replace.
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * $Data -  The string or an array with strings to search and replace
     * $nCount - If passed, this will hold the number of matched and replaced needles.
     * return:
     *  returns an array if the subject parameter is an array, or a string otherwise.
     *  if error ocured, return same $Data and triger error
     */

    public function str_replace ($sGroup,$sName,$Data,$nCount=0)
	{
        $aP = $this->GetRegularPatern($sGroup,$sName);
        $aR = $this->GetReplacement($sGroup,$sName);

        if ($nCount == 0)
            return str_replace($aP, $aR, $Data);
        else
            return str_replace($aP, $aR, $Data,$nCount);
	}

    /**
     * METHOD: preg_match
     * work identical php preg_match.
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * $sData -  The input string.
     * return:
     *  returns an array identical php preg_match.
     *  if error ocured, return emty array and triger error
     */

    public function preg_match($sGroup,$sName,&$sData)
	{
        $sP = $this->GetRegexpPatern($sGroup,$sName);
        if ($this->verify_regexp_pattern($sP))
        {
            preg_match($sP, $sData,$aResult);
            return $aResult;
        }
        else
        {
            return array();
        }
	}

    /**
     * METHOD: preg_match_all
     * work identical php preg_match_all.
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * $sData -  The input string.
     * return:
     *  returns an array identical php preg_match.
     *  if error ocured, return emty array and triger error
     */
    public function preg_match_all($sGroup,$sName,&$sData)
	{
        $sP = $this->GetRegexpPatern($sGroup,$sName);
        if ($this->verify_regexp_pattern($sP))
        {
            preg_match_all($sP, $sData,$aResult);
            return $aResult;
        }
        else
        {
            return array();
        }
	}

    /**
     * METHOD: preg_split
     * work identical php preg_split.
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * $sData -  The input string.
     * return:
     *  returns an array identical php preg_split with out delimeters and limit.
     *  if error ocured, return emty array and triger error
     */
    public function preg_split($sGroup,$sName,$sData)
	{
        $sPattern = $this->GetSplitPatern($sGroup,$sName);
        if ($this->verify_regexp_pattern($sPattern))
            return preg_split($sPattern, $sData);
        else
            return array($sData);
	}

    /**
     * METHOD: preg_split_capture_delim
     * work identical php preg_split where specified PREG_SPLIT_DELIM_CAPTURE
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * $sData -  The input string.
     * return:
     *  returns an array identical php preg_split with out limit.
     *  if error ocured, return emty array and triger error
     */
    public function preg_split_capture_delim($sGroup,$sName,$sData)
	{
        $sPattern = $this->GetSplitPatern($sGroup,$sName);
        if ($this->verify_regexp_pattern($sPattern))
            return preg_split($sPattern, $sData,-1,PREG_SPLIT_DELIM_CAPTURE);
        else
            return array($sData);
	}

    /**
     * METHOD: GetPaternReplace
     * get pattern and replace
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * return:
     *  returns
     *   array(
     *        'pattern'=>array('pattern1','pattern2',..),
     *        'replace'=>array('pattern1','pattern2',..)
     *         );
     */
    public function GetPaternReplace($sGroup,$sName='')
    {
        $this->_VerifyGroupName($sGroup,$sName);

        if (empty($sName))
        {
          $aP = $this->GetRegexpPatern($sGroup,$sName);
          return array(
              'pattern'=>$aP,
              'replace'=>$this->aTable[$sGroup]['replace']
              );
        }
        else
          return array(
              'pattern'=>$this->aTable[$sGroup]['pattern'][$sName],
              'replace'=>$this->aTable[$sGroup]['replace'][$sName]
              );
    }

    /**
     * METHOD: GetRegexpPatern
     * get pattern with seperators. For example '#\d{4}#'
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * return:
     *  returns
     *        array('pattern1','pattern2',..);
     */
    public function GetRegexpPatern($sGroup,$sName='')
    {
        $this->_VerifyGroupName($sGroup,$sName);

        if (empty($sName))
        {
            $a = array();
            foreach($this->aTable[$sGroup]['pattern'] as $k=>$v)
            {
                $s = $this->aTable[$sGroup]['d'][$k];
                $a[] = $s.$v.$s;
            }
            return $a;
        }
        else
        {
            $s = $this->aTable[$sGroup]['d'][$sName];
            return $s.$this->aTable[$sGroup]['pattern'][$sName].$s;
        }
    }

    /**
     * METHOD: GetRegexpPatern
     * get pattern with out seperators. For example '1999.10.10'
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * return:
     *  returns
     *        array('pattern1','pattern2',..);
     */

    public function GetRegularPatern($sGroup,$sName='')
    {
        $this->_VerifyGroupName($sGroup,$sName);

        if (empty($sName))
        {
            $a = array();
            foreach($this->aTable[$sGroup]['pattern'] as $k=>$v)
                $a[] = $v;

            return $a;
        }
        else
            return $this->aTable[$sGroup]['pattern'][$sName];

    }
    /**
     * METHOD: GetSplitPatern
     * join multiple paterns with "|" in one string
     *  example "pattern1|patern2|patern3"
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * return: string  "pattern1|patern2|patern3"
     */
    public function GetSplitPatern($sGroup,$sName='')
    {
        $this->_VerifyGroupName($sGroup,$sName);
        $s = '';
        if (empty($sName))
        {
            $s = current($this->aTable[$sGroup]['d']);
            return $s.'('.implode('|',$this->aTable[$sGroup]['pattern']).')'.$s;
        }
        else
        {
            $s = $this->aTable[$sGroup]['pattern'][$sName];
            return $s.'('.$this->aTable[$sGroup]['pattern'][$sName].')'.$s;
        }
    }

    /**
     * METHOD: GetReplacement
     * get replacment in array
     * params:
     * $sGroup - string group name defined in table in field group_name
     * $sName - string name defined in table in field name.
     *          If empty, load all regular expresions for $sGroup
     * return: array('replacment1','replacment2',..)
     */
    public function GetReplacement($sGroup,$sName='')
    {
        $this->_VerifyGroupName($sGroup,$sName);

        if ($sName == '')
//            return $this->aTable[$sGroup]['replace'];
            {
            $a = array();
            foreach($this->aTable[$sGroup]['replace'] as $k=>$v)
                $a[] = $v;

            return $a;

            }
        else
            return $this->aTable[$sGroup]['replace'][$sName];
    }

    /**
     * METHOD: verify_regexp_pattern
     * verify regular expresion pattern
     * params:
     * $sPattern - regularstring,  expresion pattern
     * $bTriggerError - boolean. If True, triger error on bad pattern
     *          If empty, load all regular expresions for $sGroup
     * return:
     *    True - regular expresion is valid
     *    False - regular expresion is invalid
     */
    function verify_regexp_pattern($sPattern,$bTriggerError = True)
    {
        $aPrevError = error_get_last();
        $nErrorReporting = error_reporting();
        error_reporting(0);
        preg_match($sPattern,'');
        error_reporting($nErrorReporting);
        $aLastError = error_get_last();
        if ($aPrevError != $aLastError)
        {
            if ($bTriggerError)
                trigger_error ('Ilegal pattern:'.$sPattern.'. '.$aLastError['message']);
            return False;
        }
        return true;
    }

    /**
     * METHOD: suspend_bad_regexp_pattern
     * validate regular expresion patern and invalid patterns with replacment suspend
     * $aP - regular expresion pattern
     * $aR - replacment
     */
    function suspend_bad_regexp_pattern(&$aP,&$aR)
    {
        if (is_array($aP))
        {
          foreach($aP as $k=>$v)
          {
              if (!$this->verify_regexp_pattern($v))
                  unset($aP[$k],$aR[$k]);
          }
          return (count($aP)>0);
        }
        elseif(!$this->verify_regexp_pattern($aP))
        {
            $aP=$aR='';
            return False;
        }
        else
            return True;

    }

	private function _VerifyGroupName($sGroup,$sName='')
	{
        if (empty($this->aTable[$sGroup]))
                exit ('Error: regexp_store, requested undefened  group:'.$sGroup);
        if (!empty($sName) && empty($this->aTable[$sGroup]['pattern'][$sName]))
                exit ('Error: regexp_store, requested undefened group and name:'.$sGroup.' - '.$sName);
	}

    //recursivly walk trought array and on odd elements do spliting
    function array_regexp_split($reSplitPattern,&$a)
    {
      $n = count($a)-1;
      for ($i = 0; $i <= $n; $i += 2)
      {
        if (is_array($a[$i]))
           self::array_regexp_split($reSplitPattern,$a[$i]);
        else
        {
           $aTmp = preg_split($reSplitPattern,$a[$i],-1,PREG_SPLIT_DELIM_CAPTURE);
           if (count($aTmp) > 1)
           {
              $a[$i] = $aTmp;
           }
        }
      }
    }

    //recursivly walk trought array and on odd elements do preg_replace
    function array_walk_pregreplace(&$aPattern,&$aReplace,&$a,&$nLimit,$bProcessRoot = True)
    {
      $n = count($a)-1;
      for ($i = 0; $i <= $n; $i ++)
      {
        //root delimeters - nepaara index
        if (is_odd($i) && $bProcessRoot)
        {
           if ($nLimit>0)
           {
                $a[$i] = preg_replace($aPattern, $aReplace,$a[$i]);
                $nLimit --;
           }
           else
             $a[$i] = lexp_lik_expr::_ext_link_figa($a[$i]);
        }
        elseif (is_array($a[$i]))
           self::array_walk_pregreplace($aPattern,$aReplace,$a[$i],$nLimit);
      }
    }

    //recursivly walk trought array and implode back to string
    function implode_walk(&$a)
    {
      $s = '';
      foreach($a as $k=>$v)
      {
        if (is_array($v))
            $s .= self::implode_walk($a[$k]);
        else
        {
            $s .= $v;
        }
        unset($a[$k]);
      }
      return $s;
    }

}

?>
Return current item: Regexp store