Replace mysql query table prefix in php -


i writing database query manager class.in class table prefixes characterized #__. want replace them table prefix function.

the function wrote works slow. want optimized function (maybe regex or solution).

notice: please remember #__ should not replaced in quotes.

examples :

select p.*, m.member_name, m.member_alias #__posts p left join #__members m on m.member_id=p.post_author p.post_approve = '1' , p.post_date <= '1438252218' 

or

insert `#__posts` (`post_title`, `post_text`)  values ('post title (maybe include #__ )'  , 'post text. can include #__') 

my function:

protected function replace_prefix($sql, $prefix = '#__')  {     $done = null;     $single = false;     $double = false;     $found = false;     $i = 0;     while (strlen($sql) > 0)     {         if ($sql[$i] == null)         {             return $done.$sql;         }         if (($sql[$i] == "'") && $sql[$i-1] !='\\')         {             $single = !$single;         }         if (($sql[$i] == '"') && $sql[$i-1] !='\\')         {             $double = !$double;         }          if ($sql[$i] == $prefix[0] && !$single && !$double)         {             $found = true;             ($j=0; $j < strlen($prefix); $j++)             {                 if ($sql[$i+$j] != $prefix[$j])                 {                     $found = false;                     break;                 }             }         }         if ($found)         {             $done .= substr($sql, 0, $i).$this->prefix;             $sql = substr($sql, $i+$j);             $found = false;             $i = 0;         }         else         {             $i++;         }          if ($i >= strlen($sql))         {             return $done.$sql;         }     }     return $done; } 

finally found way! function 30 times faster old:

protected function replace_prefix($sql, $prefix = '#__')  {     $array = array();     if($number = preg_match_all( '#((?<![\\\])[\'"])((?:.(?!(?<![\\\])\1))*.?)\1#i', $sql, $matches))     {         ($i = 0; $i < $number; $i++)         {             if (!empty($matches[0][$i]))             {                 $array[$i] = trim($matches[0][$i]);                 $sql = str_replace($matches[0][$i], '<#encode:'.$i.':code#>', $sql);             }         }     }      $sql = str_replace($prefix, $this->prefix , $sql);      foreach ($array $key => $js)     {         $sql = str_replace('<#encode:'.$key.':code#>', $js, $sql);     }      return $sql; } 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -