我有,用戶輸入10個號碼的一個數字代碼網站:如何在一串數字中添加破折號(自定義格式)?
xxxxxxxxxx
當顯示該值(從數據庫中讀取),我希望它以這種格式顯示:
xxxx-xxxx-xx
我怎樣才能用PHP或jQuery做到這一點?
我有,用戶輸入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>