insert dash into string
Posted: Thu Apr 10, 2008 1:05 pm
I have string that has 9 digits in it. I want to insert a dash after the 5th number. Is there a string function I can use to accomplish this?
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
preg_replace('/([0-9]{5})/i', '$1-', '123456789');Code: Select all
<?php
$str = '932348787';
$str = substr($str, 0, 5) . '-' . substr($str, 5);
?>Code: Select all
$digits = implode('-', str_split($digits, 5));Code: Select all
<?php
$new = '';
for ($i = 0; $i < strlen($str); $i++) {
$new .= $str[$i];
if ($i == 5) {
$new .= '-';
}
}
echo $new;
?>