Help with applying exception in preg_replace

时间秒杀一切 提交于 2019-12-12 05:14:34

问题


Hello How can I can I allow only digit [^0-9] and a minus sign in front the digit. Example : Valid = -1...-9, Invalid = --1-...


回答1:


Just remove every invalid character and check if the remaining has a valid format:

$cleaned = preg_replace('/[^-0-9]+/', '', $str);
if (preg_match('/^-?[0-9]+$/', $cleaned)) {
    // now valid
}

Ok, here’s another suggestion:

preg_replace('/.*?(-?\d+).*/', '$1', $str)



回答2:


/^-\d+$/

or if minus is optional

/^-?\d+$/



回答3:


Should be as simple as...

preg_match('#^-?[0-9]$#', $input);

Update

preg_replace('#-\d#', $replacement, $input);


来源:https://stackoverflow.com/questions/3365874/help-with-applying-exception-in-preg-replace

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