Skip to content

Instantly share code, notes, and snippets.

@mahfuzul
Last active September 26, 2023 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahfuzul/7b12584fff12b01e40abcca937797595 to your computer and use it in GitHub Desktop.
Save mahfuzul/7b12584fff12b01e40abcca937797595 to your computer and use it in GitHub Desktop.
Convert string of numbers to SSN format in PHP
// Format string to SSN (Social Security Number) in the format of XXX-XX-XXXX
function string_to_ssn( $ssn = "111223333" ) {
return substr($ssn, 0, 3).'-'.substr($ssn, 3, 2).'-'.substr($ssn,5);
}
// Format string to SSN by preg_replace
function string_to_ssn_2( $ssn = "111223333" ) {
$ssn = preg_replace('/[^\d]/', '', $ssn);
$ssn = preg_replace('/^(\d{3})(\d{2})(\d{4})$/', '$1-$2-$3', $ssn);
return($ssn);
}
@mankowitz
Copy link

what if it's an int?

@mahfuzul
Copy link
Author

convert it to a string first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment