Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace spaces between the last 4 digits

I know how to remove spaces from a string:

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

But what if I need to remove spaces ONLY between 4 last digits of ANY number?

As an example:

12895 6 7 8 9 - I want it to become 12895 6789

or

2546734 34 55 - I want it to become 2546734 3455

or

2334734556 341 5 - I want it to become 2334734556 3415

How do I do that?

** Update: I want to remove spaces between the last four digits not after the first space (since all examples show the space). So something like that would be a better example:

23347345563 4 1 5 - I want it to become 23347345563415

like image 649
MrVK Avatar asked Jan 29 '26 22:01

MrVK


1 Answers

You can achieve what you want with preg_replace and this regular expression:

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

which looks for a space followed by 0 to 3 digits (with optional spaces) between it and the end of the line (using a positive lookahead). Simply replace those spaces with an empty string (''):

$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";

Output:

12895 6789
2546734 3455
2334734556 3415
23347345563415

Demo on 3v4l.org

like image 103
Nick Avatar answered Feb 01 '26 16:02

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!