开发者

How can I add dashes (custom formatting) inside a string of numbers?

开发者 https://www.devze.com 2022-12-13 04:45 出处:网络
I have a site where users enter a numeric code of 10 numbers: xxxx开发者_运维知识库xxxxxx When displaying this value (read from the database), I want it to display in this format:

I have a site where users enter a numeric code of 10 numbers:

xxxx开发者_运维知识库xxxxxx

When displaying this value (read from the database), I want it to display in this format:

xxxx-xxxx-xx

How can I do this with PHP or jQuery?


$code = "1234567890";
echo substr($code, 0, 4) . "-" . substr($code, 4, 4) . "-" . substr($code, 8, 2);


You can use Regular Expression.

$Text        = "1234567890";
$Pattern     = '/(.{4})(.{4})(.{2})/';
$Replacement = '$1-$2-$3';
$NewText     = preg_replace($Pattern, $Replacement, $Text);

Hope this helps.


in jquery, for example:

<script>
    $(document).ready(function(){
        n = $("#IdOfTheElement").text();
        n = n.substr(0, 4) + "-" + n.substr(4, 4) + "-" + n.substr(8);
        $("#IdOfTheElement").text(n)
    }
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消