I am writing a database query manager class.In my class table prefixes are characterized by #__. I want to replace them to table prefix by a function.
The function that i wrote works well but it is very slow. i want a optimized function (maybe regex or another solution).
Notice: please remember that #__ should not be replaced in quotes.
examples :
SELECT p.*, m.member_name, m.member_alias
FROM #__posts AS p
LEFT JOIN #__members AS m ON m.member_id=p.post_author
WHERE p.post_approve = '1' AND p.post_date <= '1438252218'
OR
INSERT INTO `#__posts` (`post_title`, `post_text`)
VALUES ('post title (maybe include #__ )' , 'post text. it also 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;
for ($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;
}