Reputation: 33
$reg1 = preg_replace('/(?<!\d),(?=\s+\d)/', '', $text);
$reg2 = preg_replace('/,\s*$/', '', $reg1);
$reg3 = preg_replace('/\s\s+/', ' ', $reg2);
I have these three regex-replace calls. Can I combine those in one? The first one removes commas after strings and before digits. The second one removes a comma at the end. The third one trims whitespace.
Upvotes: 1
Views: 118
Reputation: 82
Due to the different replacement values, you can only group your first 2 regex with an "or" condition. preg_replace
also allow multiple replacements, so you can pass the 3rd regex as a separate argument.
$result = preg_replace(array('/((?<!\d),(?=\s+\d))|(,\s*$)/', '(\s\s+)'), array('', ' '), $text);
Upvotes: 1
Reputation: 91373
The first two can be combined like:
$reg1 = preg_replace('/(?<!\d),\s*(?=\d|$)/', '', $text);
Upvotes: 2
Reputation: 6785
You could pass all three to preg_replace
:
$patterns = array('/(?<!\d),(?=\s+\d)/', '/,\s*$/', '/\s\s+/');
$replacements = array('', '', ' ');
$result = preg_replace($patterns, $replacements, $text);
Upvotes: 0