简体   繁体   English

如何格式化英国银行的分类代码?

[英]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 . 排序代码以六个数字(例如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. 我想使用PHP在站点的一个区域中输出排序代码,但格式为77-17-31

I have searched Google for a solution but surprisingly found very little. 我已经在Google上搜索了解决方案,但令人惊讶的是,发现的很少。

This is the prefect use-case for wordwrap() , just use it like this: 这是wordwrap()的完美用例,只需像这样使用它:

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

output: 输出:

77-17-31

Just figured this out using PHP functions, thought I'd post the answer in case it helped anyone else doing a Google search... 刚刚使用PHP函数弄清楚了这一点,以为我会发布答案,以防它帮助其他人进行Google搜索...

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

echo formatSortCode('771731'); // outputs 77-17-31

I arrived here looking for a JavaScript answer not realising it was a PHP question. 我来到这里寻找JavaScript答案,但没有意识到这是一个PHP问题。 Tweaking @MichaelLB's answer, the JavaScript translation is 调整@MichaelLB的答案, JavaScript翻译是

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

formatSortCode(123456789);

>>> "12-34-56-78-9"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM