0

As part of a form I collect a users bank details which includes their sort code. The sort code is stored in the database as six numbers, for example 771731.

I'd prefer to store the sort code in this format (without the hyphens) as it makes it easier for me to work with in other areas of the site. I want to output the sort code in one area of the site but in the format 77-17-31 using PHP.

I have searched Google for a solution but surprisingly found very little.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Michael LB
  • 2,715
  • 4
  • 23
  • 38

3 Answers3

8

This is the prefect use-case for wordwrap(), just use it like this:

$code = "771731";
echo wordwrap($code, 2, "-", TRUE);

output:

77-17-31
Rizier123
  • 58,877
  • 16
  • 101
  • 156
1

Just figured this out using PHP functions, thought I'd post the answer in case it helped anyone else doing a Google search...

function formatSortCode($str) {
    return implode("-", str_split($str, 2));
}

echo formatSortCode('771731'); // outputs 77-17-31
Michael LB
  • 2,715
  • 4
  • 23
  • 38
1

I arrived here looking for a JavaScript answer not realising it was a PHP question. Tweaking @MichaelLB's answer, the JavaScript translation is

function formatSortCode(str) {
    return (String(str).match(/.{1,2}/g) || []).join('-');
}

formatSortCode(123456789);

>>> "12-34-56-78-9"
Luke Madhanga
  • 6,871
  • 2
  • 43
  • 47
  • I arrived here too and decided to create a post with the Javascript question on. https://stackoverflow.com/questions/75447296/how-do-i-format-an-account-name-and-or-sort-code-using-javascript – Watts Epherson Feb 14 '23 at 11:52