Skip to main content
Inspiring
March 3, 2011
Answered

Formatting Number with Regular Expression and PHP preg_replace

  • March 3, 2011
  • 1 reply
  • 1215 views

Hi,

I would like to add a “dash” after every 3 digits in a given numbers (10 digits). For example, 9785678941 became 978-567-894-1. How could I achieve this with regular expression by using PHP preg_replace?

Thank you.

This topic has been closed for replies.
Correct answer Günter_Schenk

The following solution is based on the "Using backreferences followed by numeric literals" example published on the php.net website.

In compliance with the $string, $pattern, $replacement nomenclature which the php.net example makes use of, here´s my modification:

<?php

$string = '9785678941';

$pattern = '/(\\d{3})(\\d{3})(\\d{3})(\\d{1})/';

$replacement = '${1}-${2}-${3}-${4}';

echo preg_replace($pattern, $replacement, $string);

?>

1 reply

Günter_Schenk
Günter_SchenkCorrect answer
Inspiring
March 3, 2011

The following solution is based on the "Using backreferences followed by numeric literals" example published on the php.net website.

In compliance with the $string, $pattern, $replacement nomenclature which the php.net example makes use of, here´s my modification:

<?php

$string = '9785678941';

$pattern = '/(\\d{3})(\\d{3})(\\d{3})(\\d{1})/';

$replacement = '${1}-${2}-${3}-${4}';

echo preg_replace($pattern, $replacement, $string);

?>

Inspiring
March 4, 2011

Dear Günter,

Thank you very much for the solution. It works. By the way, this regex applied to string with exact length (ie., 10 digits in this case) but break if the string has different length, ie., 14 digits. Is it possible to modify the regex so that it always add a dash after every 3 digits at any string length?

Thank you very much and have a nice day.

Best regards,

Edwin

Günter_Schenk
Inspiring
March 4, 2011

Hi Edwin,

Is it possible to modify the regex so that it always add a dash after every 3 digits at any string length?

Let´s better skip the regex approach and resort to native PHP string/array functionality:

<?php

$string = '978567894';

$array = str_split($string,3);

$count=sizeof($array);

for($x=0;$x<$count;$x++){

$lastkey = array_pop(array_keys($array));

if ($x==$lastkey) {

$delimiter = "";

}

else {

$delimiter = "-";

}

echo $array[$x].$delimiter;

}

?>

Well, I´m currently in some sort of "let others explain what I´m doing" mood, so if you or other participants don´t mind, I´d like to know...

a) whats the purpose of $array = str_split($string,3);

b) which line evaluates the size of an array

c) which line identifies and stores the last value of an array, and why do you need this in reference to the $delimiter variable

Looking forward to the replies ;-)

Cheers,

Günter