preg_replace 最后 4 位数字之间的空格

preg_replace spaces between the last 4 digits

我知道如何从字符串中删除 spaces:

$text = preg_replace('/\s+/', '', $text);

但是如果我只需要删除任何数字的最后 4 位之间的 space 怎么办?

例如:

12895 6 7 8 9 - 我希望它变成 12895 6789

2546734 34 55 - 我希望它变成 2546734 3455

2334734556 341 5 - 我希望它变成 2334734556 3415

我该怎么做?

** 更新:我想删除最后四位数字之间的 spaces 而不是第一个 space 之后(因为所有示例都显示 space)。所以类似这样的例子会更好:

23347345563 4 1 5 - 我希望它变成 23347345563415

function func($text, $digits = 4){
  $str = '';
  for ($i = strlen($text)-1; $i >= 0; $i--){
    if(strlen($str) < $digits && !is_numeric($text[$i]))continue;
    $str .= $text[$i];
  }
  return strrev($str);
}

$text1 = '12895 6 7 8 9';
$text2 = '2546734 34 55';
$text3 = '2334734556 341 5';


echo func($text1, 4);   //12895 6789
echo func($text2, 4);   //2546734 3455
echo func($text3, 4);   //2334734556 3415

如果您正在寻找使用正则表达式的内容,请查看下面的示例。它使用匹配来获取字符串的不同部分,然后以正确的格式将其连接回来。

$strings = [
    '12895 6 7 8 9',
    '2546734 34 55',
    '2334734556 341 5',
];

function formatNumber($number)
{
    preg_match('/(\d+) ?((?:[\d]\s*){4})$/', $number, $matches);

    if (!$matches) {
        return $number;
    }

    return sprintf('%s %s', $matches[1], str_replace(' ', '', $matches[2]));
}

var_dump(array_map('formatNumber', $strings));

输出:

array(3) {
  [0] =>
  string(10) "12895 6789"
  [1] =>
  string(12) "2546734 3455"
  [2] =>
  string(15) "2334734556 3415"
}

你可以用 preg_replace 和这个正则表达式来实现你想要的:

\s+(?=(\d\s*){0,3}$)

查找 space 后跟 0 到 3 位数字(可选 spaces)在它和行尾之间(使用正前瞻)。只需将 space 替换为空字符串 (''):

$text = preg_replace('/\s+(?=(\d\s*){0,3}$)/', '', '12895 6 7 8 9');
echo "$text\n";
$text = preg_replace('/\s+(?=(\d\s*){0,3}$)/', '', '2546734 34 55');
echo "$text\n";
$text = preg_replace('/\s+(?=(\d\s*){0,3}$)/', '', '2334734556 341 5');
echo "$text\n";
$text = preg_replace('/\s+(?=(\d\s*){0,3}$)/', '', '23347345563 4 1 5');
echo "$text\n";

输出:

12895 6789
2546734 3455
2334734556 3415
23347345563415

Demo on 3v4l.org