Reputation: 520
I am using a lib which uses
$pattern = "LIMIT[^\w]{1,}([0-9]{1,})([\,]{0,})([0-9]{0,})";
$replacement = "";
eregi($pattern, $query, $regs);
$query = eregi_replace($pattern, $replacement, $query);
if($regs[2])
$query = str_ireplace("SELECT ", "SELECT TOP ".$regs[3]." ", $query);
else
{
if($regs[1])
$query = str_ireplace("SELECT ", "SELECT TOP ".$regs[1]." ", $query);
}
I change some part of the code to
$pattern = "/LIMIT[^\w]{1,}([0-9]{1,})([\,]{0,})([0-9]{0,})/i";
$replacement = "";
preg_match($pattern, $query, $regs);
But now I got error messages saying "Undefined offset: 2" and "Undefined offset: 1"
I think moving from eregi to preg_match should be easy...
Upvotes: 0
Views: 229
Reputation: 56915
There is no issue with preg_match
or preg_replace
or your regex.
You get this error when $query
doesn't match at all (e.g. $query="SELECT foo FROM bar"
).
Then $regs
is an empty array, so accessing $regs[2]
results in an error since there are no elements in it to begin with.
I'd suggest using count($regs)
to see whether to even do the $regs[2]
thing.
$query="SELECT asdf FROM foo";
$pattern = "/LIMIT[^\w]{1,}([0-9]{1,})([\,]{0,})([0-9]{0,})/i";
$replacement = "";
preg_match($pattern, $query, $regs);
$query = preg_replace($pattern, $replacement, $query);
if( count($regs)>=0 ) {
if($regs[2])
// ... etc the #$egs[2] $regs[1] code here.
}
Upvotes: 1