Charlie Sheather
Charlie Sheather

Reputation: 2374

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 trying 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

Upvotes: 0

Views: 148

Answers (1)

Paul Dixon
Paul Dixon

Reputation: 300985

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);

Upvotes: 1

Related Questions