note 50327 deleted from function.substr by googleguy

From: Date: Tue, 22 Oct 2013 10:15:28 +0000
Subject: note 50327 deleted from function.substr by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-196946@lists.php.net to get a copy of this message
Note Submitter: Matias from Argentina ---- Hello, Here you are a function to format your numeric strings. Enjoy it. <?php function str_format_number($String, $Format){ if ($Format == '') return $String; if ($String == '') return $String; $Result = ''; $FormatPos = 0; $StringPos = 0; While ((strlen($Format) - 1) >= $FormatPos){ //If its a number => stores it if (is_numeric(substr($Format, $FormatPos, 1))){ $Result .= substr($String, $StringPos, 1); $StringPos++; //If it is not a number => stores the caracter } Else { $Result .= substr($Format, $FormatPos, 1); } //Next caracter at the mask. $FormatPos++; } return $Result; } // For phone numbers at Buenos Aires, Argentina // Example 1: $String = "541143165500"; $Format = "+00 00 0000.000"; Echo str_format_number($String, $Format); // Returns "+54 11 4316.5500" // Example 2: $String = "541143165500"; $Format = "+00 00 0000.0000000"; Echo str_format_number($String, $Format); // Returns "+54 11 4316.5500" // Example 3: $String = "541143165500"; $Format = "+00 00 0000.000 a"; Echo str_format_number($String, $Format); // Returns "+54 11 4316.550 a" ?> How it works explanation: str_format_number($String, $Format) Spects two parameters $String and $Format, both should be strings. $String: coulbe any kind of data type, but it's oriented to numeric string, like phone numbers. $Format: should be a conjunction between numbers (any one) and others caracters. str_format_number takes each caracter of $Format, if it isn't a number stores it to be returned later, but if it is a number takes the caracter of $String placed in the position corresponding to the amount of numbers in $Format so far starting from zero. If $Format has less numbers than $string caracters the rest of the caracters at the end of $String should be ignored. If $Format has more numbers than $string caracters the no caracter will be used, so those will be ignored.

« previous php.notes (#196946) next »