2011-11-15 73 views
-1

可能重複:
Converting ereg expressions to pregPHP 5.3 eregi_replace到的preg_replace

我試圖解決一些舊代碼,使其與PHP 5.3的作品。 希望第一次轉換到str_replace是可以的,但我完全不確定第二次轉換爲preg_replace。

任何幫助將非常感激。由於

$this->Query = str_replace(" where "," WHERE ", $this->Query); 
$this->Query = str_replace(" select "," SELECT ", $this->Query); 
$this->Query = str_replace(" from "," FROM ", $this->Query); 
$this->Query = str_replace(" as "," AS ", $this->Query); 

// $this->Query = eregi_replace(" WHERE ", " where ", $this->Query); 
// $this->Query = eregi_replace("SELECT ", "select ", $this->Query); 
// $this->Query = eregi_replace(" FROM ", " from ", $this->Query); 
// $this->Query = eregi_replace(" AS ", " as ", $this->Query); 

$TempQuery = eregi_replace("^select .* from ", "select count(1) from ", $this->Query); 
$TempQuery = eregi_replace(" order by .*$", "", $TempQuery); 
+7

你確實知道SQL不一定是大寫的? (並且你做了與eregi_replace完全相反的操作) – yoavmatchulsky

+0

請參閱PCRE語法http://php.net/manual/en/reference.pcre.pattern.syntax.php – BoltClock

+0

你可以這樣做,'preg_replace ('/ pattern_here /我','替換',$主題)',但爲什麼要經歷這一切麻煩?查詢將以任何方式工作。 – Shef

回答

1

至於說,SQL語法不必是大寫......不過無論如何回答你的問題:

$TempQuery = preg_replace("/^select .*? from /i", "select count(1) from ", $this->Query); 
$TempQuery = preg_replace("/ order by .*?$/i", "", $TempQuery); 

這應該工作。我對正則表達式不區分大小寫,因爲你似乎遇到了大寫和小寫的問題。此外,我通過添加一個問號以避免額外的複雜性而使得.*不明確。

1

* eregi_replace *必須是*的preg_replace *代替

例如:

$string = $this->Query; 
$pattern = '/^select .* from /i'; 
$replacement = "select count(1) from "; 
$TempQuery = preg_replace($pattern, $replacement, $string); 
+0

非常感謝,似乎很簡單,添加分隔符和'我'結束。乾杯 – TSUK