开发者

PHP - preg_replace simplify?

haven't used regex replaces much and am not sure if how I have done this is the best way of doing it. Im tryi开发者_运维知识库ng to change eg:

'(.123.)' OR 123.)' OR '(.123

to

'.(123).' OR 123).' OR '.(123

must be an int in the middle.

preg_replace('/\.\)/', ').',preg_replace('/\(\./', '.(',preg_replace('/(\.[0-9]+\.)|(\.[0-9]+|[0-9]+\.)/', '($0)',$str)));

the code I have above works, just wondering if there is a better way to do it


Could you do more simply in two replacements, one for (. before a digit and one for .) after a digit?

$str=preg_replace('/\(\.(\d)/', '.($1', $str);
$str=preg_replace('/(\d)\.\)/', '$1).', $str);

It's even possible to do this in one go, but it looks uglier. Here I look for a number preceded by (. and optionally followed by .), or optionally preceded by (. and followed by .), then replace the whole lot with .(number). - this has the effect of turning .(123 into .(123)., which you may or may not want...

$str=preg_replace('/\(\.(\d+)(?:\.\))?|(?:\(\.)?(\d+)\.\)/', '.($1$2).', $str);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜