Merge branch 'maint/7.0'
[ninja.git] / system / helpers / format.php
blob29cb563313876c2b58960d39ac85146d261fd600
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3 * Format helper class.
5 * $Id: format.php 3917 2009-01-21 03:06:22Z zombor $
7 * @package Core
8 * @author Kohana Team
9 * @copyright (c) 2007-2008 Kohana Team
10 * @license http://kohanaphp.com/license.html
12 class format {
14 /**
15 * Formats a phone number according to the specified format.
17 * @param string phone number
18 * @param string format string
19 * @return string
21 public static function phone($number, $format = '3-3-4')
23 // Get rid of all non-digit characters in number string
24 $number_clean = preg_replace('/\D+/', '', (string) $number);
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);
29 // Number must match digit count of a valid format
30 if (strlen($number_clean) !== array_sum($format_parts))
31 return $number;
33 // Build regex
34 $regex = '(\d{'.implode('})(\d{', $format_parts).'})';
36 // Build replace string
37 for ($i = 1, $c = count($format_parts); $i <= $c; $i++)
39 $format = preg_replace('/(?<!\$)[1-9][0-9]*/', '\$'.$i, $format, 1);
42 // Hocus pocus!
43 return preg_replace('/^'.$regex.'$/', $format, $number_clean);
46 /**
47 * Formats a URL to contain a protocol at the beginning.
49 * @param string possibly incomplete URL
50 * @return string
52 public static function url($str = '')
54 // Clear protocol-only strings like "http://"
55 if ($str === '' OR substr($str, -3) === '://')
56 return '';
58 // If no protocol given, prepend "http://" by default
59 if (strpos($str, '://') === FALSE)
60 return 'http://'.$str;
62 // Return the original URL
63 return $str;
66 } // End format