phpformatbank

How to format a UK bank sort code?


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.


Solution

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

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

    output:

    77-17-31