如何在一串数字中添加破折号(自定义格式)?
问题描述:
我有,用户输入10个号码的一个数字代码网站:如何在一串数字中添加破折号(自定义格式)?
xxxxxxxxxx
当显示该值(从数据库中读取),我希望它以这种格式显示:
xxxx-xxxx-xx
我怎样才能用PHP或jQuery做到这一点?
答
$code = "1234567890";
echo substr($code, 0, 4) . "-" . substr($code, 4, 4) . "-" . substr($code, 8, 2);
答
您可以使用正则表达式。
$Text = "1234567890";
$Pattern = '/(.{4})(.{4})(.{2})/';
$Replacement = '$1-$2-$3';
$NewText = preg_replace($Pattern, $Replacement, $Text);
希望这会有所帮助。
答
在jquery的,例如:
<script>
$(document).ready(function(){
n = $("#IdOfTheElement").text();
n = n.substr(0, 4) + "-" + n.substr(4, 4) + "-" + n.substr(8);
$("#IdOfTheElement").text(n)
}
</script>