Copy link to clipboard
Copied
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.
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);
?>
Copy link to clipboard
Copied
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);
?>
Copy link to clipboard
Copied
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
Copy link to clipboard
Copied
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
Copy link to clipboard
Copied
Dear Günter,
Thank you very much for the looping solution.
Best regards,
Edwin
Get ready! An upgraded Adobe Community experience is coming in January.
Learn more