1

有没有一种方法可以preg_replace用来替换Afor Bif Ais present 或Bfor Aif Bis present?

就像是:

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

将 anyORDER BY field ASC转换为ORDER BY field DESC,并将 anyORDER BY field DESC转换为ORDER BY field ASC

4

1 回答 1

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);
于 2013-01-02T10:48:58.920 回答