Warning: preg_replace() [function.preg-replace]: Compilation failed: nothing to repeat at offset 1

放肆的年华 提交于 2020-01-29 13:33:26

问题


Can someone help debug this error?

Warning: preg_replace() [function.preg-replace]: Compilation failed: nothing to repeat at offset 1

//Generate uid
    function gen_uid($len=40) {
        $hex = md5("what" . uniqid("", true));
        $pack = pack('H*', $hex);
        $tmp =  base64_encode($pack);
        $uid = preg_replace("#(*UTF8)[^A-Za-z0-9]#", "", $tmp);
        $len = max(4, min(128, $len));
        while (strlen($uid) < $len)
            $uid .= gen_uid(22);
        return substr($uid, 0, $len);
    }

What causes this? Is it a PHP issue or something else? The application works fine on my local machine but not on the server.


回答1:


* in regex means to match the previous character 0 or more times, while ( starts a capturing group. So, the * has nothing to repeat, since what comes before the * is a (, which cannot be repeated by itself, hence this warning.

To fix it, just escape the *, like so:

$uid = preg_replace("#(\*UTF8)[^A-Za-z0-9]#", "", $tmp);


来源:https://stackoverflow.com/questions/12266372/warning-preg-replace-function-preg-replace-compilation-failed-nothing-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!