使用正则表达式删除数字分隔符

I'm looking for a simple stupid solution, to remove delimiters from numbers within strings.

This function replaces 2.000 BC with 2000 BC:

$text preg_replace("/^[0-9.]+$/", "", $text);

Example:

$text = 'Lorem ipsum dolor. Consetetur elitr 2.000 BC sed diam nonumy 300.'

// Current behaviour (the delimeter at the end ot the line disappears):
// Lorem ipsum dolor. Consetetur elitr 2000 BC sed diam nonumy 300

// Expected behaviour:
// Lorem ipsum dolor. Consetetur elitr 2000 BC sed diam nonumy 300.

You can replace (?<=\d)\.(?=\d) with nothing:

<?php

$text = 'Lorem ipsum dolor. Consetetur elitr 2.000 BC sed diam nonumy 300.';

$text = preg_replace('/(?<=\d)\.(?=\d)/', '', $text);

var_dump($text);

//string(64) "Lorem ipsum dolor. Consetetur elitr 2000 BC sed diam nonumy 300."

DEMO

Regex autopsy:

Regular expression visualization

  • (?<=\d) - a positive lookbehind matching a digit (this will not be replaced) - essentially this requires the . to be preceeded by a digit
  • \. - a literal . character, escaped as . means "any character" in regex
  • (?<=\d) - a positive lookahead matching a digit (this will not be replaced) - essentially this requires the . to be followed by a digit

To match the delimiter present only inside a number,

\d+\K\.(?=\d+)

DEMO

IDEONE

Your PHP code should be,

<?php
$string = 'Lorem ipsum dolor. Consetetur elitr 2.000 BC sed diam nonumy 300.';
$pattern = "~\d+\K\.(?=\d+)~";
$replacement = "";
echo preg_replace($pattern, $replacement, $string);
?>

Output:

Lorem ipsum dolor. Consetetur elitr 2000 BC sed diam nonumy 300.

Explanation:

  • \d+ One or more digits.
  • \K Discards the previously matched characters.
  • .(?=\d+) Matches a literal dot which should be followed by one or more digits.