I use the following function to filter numbers from a string (including some special cases such as prices (starting with $)):
function _process_numbers($string) {
return preg_replace(
'/(?<!\{) # Assert no preceding {
(?<![^\s$-]) # Assert no preceding non-whitespace except $-
\b # Match start of number
(\d+(?:\.\d+)?+) # Match number (optional decimal part)
\b # Match end of number
(?![^{}]*\}) # Assert that next brace is not a closing brace
(?![^\s.!?,%]) # Assert no following non-whitespace except .!?,%
/x',
'{NUMBER|\1}', $string
);
}
echo _process_numbers("100.000.000 and -0.33 and $100.50 and 0.06%");
This works rather well, except that (1) the minus “-” should be included inside the braces of the output and (2) numbers up to 1 billion (and minus one billion) should be supported. In other words; the above returns as output:
{NUMBER|100.000}.000 and -{NUMBER|0.33} and ${NUMBER|100.50} and {NUMBER|0.06}%
But the expected output is:
{NUMBER|100.000} and {NUMBER|-0.33} and ${NUMBER|100.50} and {NUMBER|0.06}%
What should be changed?
should do the trick:
UPDATE
remove the – from the look-behind assertion, capture the first (
\bor-).