2013-01-02 118 views
1

有使用preg_replace更換AB如果A存在的一種方式,或爲B如果AB存在?更換爲B,或B對於A

喜歡的東西:

preg_replace('/ORDER BY field (ASC|DESC)/', 'ORDER BY field (***the alternative not matched***)'); 

變換任何ORDER BY field ASCORDER BY field DESC,任何ORDER BY field DESCORDER BY field ASC

回答

6

您正在尋找的功能是preg_replace_callback。

例子:

function replace_asc_desc($matches) 
{ 
    return 'ORDER BY field ' . ($matches[1] == 'ASC' ? 'DESC' : 'ASC'); 
} 

$string = 'ORDER BY field DESC'; 

echo preg_replace_callback('/ORDER BY field (ASC|DESC)/', 'replace_asc_desc', $string); 
+0

謝謝!那是我需要的。 –

相關問題