Initial Kohana install
[speedfreak] / Server / system / helpers / format.php
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3  * Format helper class.
4  *
5  * $Id: format.php 4070 2009-03-11 20:37:38Z Geert $
6  *
7  * @package    Core
8  * @author     Kohana Team
9  * @copyright  (c) 2007-2008 Kohana Team
10  * @license    http://kohanaphp.com/license.html
11  */
12 class format_Core {
13
14         /**
15          * Formats a phone number according to the specified format.
16          *
17          * @param   string  phone number
18          * @param   string  format string
19          * @return  string
20          */
21         public static function phone($number, $format = '3-3-4')
22         {
23                 // Get rid of all non-digit characters in number string
24                 $number_clean = preg_replace('/\D+/', '', (string) $number);
25
26                 // Array of digits we need for a valid format
27                 $format_parts = preg_split('/[^1-9][^0-9]*/', $format, -1, PREG_SPLIT_NO_EMPTY);
28
29                 // Number must match digit count of a valid format
30                 if (strlen($number_clean) !== array_sum($format_parts))
31                         return $number;
32
33                 // Build regex
34                 $regex = '(\d{'.implode('})(\d{', $format_parts).'})';
35
36                 // Build replace string
37                 for ($i = 1, $c = count($format_parts); $i <= $c; $i++)
38                 {
39                         $format = preg_replace('/(?<!\$)[1-9][0-9]*/', '\$'.$i, $format, 1);
40                 }
41
42                 // Hocus pocus!
43                 return preg_replace('/^'.$regex.'$/', $format, $number_clean);
44         }
45
46         /**
47          * Formats a URL to contain a protocol at the beginning.
48          *
49          * @param   string  possibly incomplete URL
50          * @return  string
51          */
52         public static function url($str = '')
53         {
54                 // Clear protocol-only strings like "http://"
55                 if ($str === '' OR substr($str, -3) === '://')
56                         return '';
57
58                 // If no protocol given, prepend "http://" by default
59                 if (strpos($str, '://') === FALSE)
60                         return 'http://'.$str;
61
62                 // Return the original URL
63                 return $str;
64         }
65
66 } // End format