1: <?php
2:
3: /**
4: * Pry Framework
5: *
6: * LICENSE
7: *
8: * This source file is subject to the new BSD license that is bundled
9: * with this package in the file LICENSE.txt.
10: *
11: * @version $Revision: 276 $
12: */
13:
14: /**
15: * Classe String
16: *
17: * Class de gestion de string
18: *
19: * @category Pry
20: * @package Util
21: * @version 1.9.0
22: * @author Olivier ROGER <oroger.fr>
23: *
24: */
25: class Util_String
26: {
27:
28: /**
29: * Ajout de slashe. Ajoute des slashes si magiquotes desactivé
30: * @access public
31: * @param string $chaine Chaine à traiter
32: * @static
33: * @return string Chaine complétée par des /
34: */
35: public static function slashes($chaine)
36: {
37: if (!get_magic_quotes_gpc())
38: $chaine = addslashes($chaine);
39:
40: return $chaine;
41: }
42:
43: /**
44: * Nettoyage de chaine. Reécrit une chaine pour supprimer espace et caractère spéciaux, accentués ...
45: * @access public
46: * @param string $titre Chaine à traiter
47: * @param string $delimiter Charactère délimiteur
48: * @static
49: * @return string chaine modifiée
50: * */
51: public static function clean($string, $delimiter = "_")
52: {
53: //Transformation des apostrophe en espace pour avoir :
54: // c'est = "c-est" et non pas "cest"
55: $string = str_replace("'", ' ' , $string);
56:
57: $cleanStr = iconv('UTF-8', 'ASCII//TRANSLIT', $string); //Suppression accent
58: $cleanStr = trim(strtolower($cleanStr));
59: $cleanStr = preg_replace("/[^a-z0-9\/_|+ -]/", '', $cleanStr);
60: $cleanStr = preg_replace("/[\/_|+ -]+/", $delimiter, $cleanStr);
61:
62: return $cleanStr;
63:
64: }
65:
66: /**
67: * Découpe de chaine. Découpe une chaine au nombre de mot souhaité
68: * @access public
69: * @param string $chaine Chaine à traiter
70: * @param int $taillemax Nombre de caractère maxi
71: * @param string $end Caractère affiché en cas de césure (... par défaut)
72: * @static
73: * @return string Chaine tronquée
74: */
75: public static function cut($chaine, $taillemax, $end="...")
76: {
77: if (strlen($chaine) >= $taillemax)
78: {
79: $chaine = substr($chaine, 0, $taillemax);
80: $espace = strrpos($chaine, " ");
81: $chaine = trim(substr($chaine, 0, $espace) . $end);
82: }
83: return $chaine;
84: }
85:
86: /**
87: * Génération "aléatoire". Génère une string de longeur $taille.
88: * La génération favorise les chaines facilement mémorisable
89: * @access public
90: * @param int $taille Taille de la chaine désirée
91: * @static
92: * @return string
93: */
94: public static function generate($taille)
95: {
96:
97: //Consonnes
98: $cons = 'bBcCdDfFgGhHjJkKlLmMnNoOpPqQrRsStTvVwWxXzZ@!#$%123465789';
99: //Voyelles
100: $voy = 'aAeEuUyY123465789'; // pas de o et i pour éviter confusion
101: $genere = '';
102: $genere.= $cons[rand(0, 41)]; // On commence forcément par une lettre
103: for ($i = 1; $i <= ($taille - 1); $i++) {
104: if ($i % 2 == 0)
105: $genere.=$cons[(rand(0, strlen($cons) - 1))];
106: else
107: $genere.=$voy[(rand(0, strlen($voy) - 1))];
108: }
109: return $genere;
110: }
111:
112: /**
113: * Retourne une chaine sous le format camelCase
114: *
115: * @param string $string
116: * @return string
117: */
118: public static function camelize($string)
119: {
120: return preg_replace("/[_|\s]([a-z0-9])/e", "strtoupper('\\1')", strtolower($string));
121: }
122:
123: /**
124: * Fonction de geekiserie pour des propos plus intelligents
125: *
126: * @param string $string
127: * @return string
128: */
129: public static function geekize($string)
130: {
131: $string = strtolower($string);
132: $normal = array('a', 'e', 't', 'l', 's', 'o');
133: $geek = array('4', '3', '7', '1', '$', '0');
134: return str_replace($normal, $geek, $string);
135: }
136:
137: /**
138: * Anti majuscule. Vérifie que la chaine ne comporte pas trop de majuscule (50%)
139: * @access public
140: * @param string $string Chaine à vérifier
141: * @static
142: * @return La chaine modifié si trop de maj ou la chaine original si ok
143: */
144: public static function hasTooMuchCaps($string)
145: {
146: $seuil = strlen($string) / 2;
147: $correspondance = similar_text($pseudo, strtolower($string));
148: if ($correspondance < $seuil)
149: return strtolower($string);
150:
151: return $string;
152: }
153:
154: /**
155: * Vérifie si une chaine est en majuscule
156: *
157: * @param string $string Chaine d'entrée
158: * @return boolean
159: */
160: public static function isUpper($string)
161: {
162: if (preg_match("/[a-z]/", $string) > 0)
163: return false;
164: return true;
165: }
166:
167: /**
168: * Vérifie si une chaine est en minuscule
169: *
170: * @param string $string Chaine d'entrée
171: * @return boolean
172: */
173: public static function isLower($string)
174: {
175: if (preg_match("/[A-Z]/", $string) > 0)
176: return false;
177: return true;
178: }
179:
180: /**
181: * Vérification IP. Vérifie que la chaine est une ip valide
182: * @access public
183: * @param string $ip Adresse Ip à vérifier
184: * @static
185: * @return boolean
186: */
187: public static function isIp($ip)
188: {
189: $motif = '`^([0-9]{1,3}\.){3}[0-9]{1,3}$`';
190: if (preg_match($motif, $ip))
191: {
192: $ipArray = explode(".", $ip);
193: for ($i = 0; $i < 4; $i++)
194: if ($ipArray[$i] > 255)
195: return false;
196:
197: return true;
198: }
199: else
200: return false;
201: }
202:
203: /**
204: * Vérification MAC. Vérifie que la chaine est une adresse MAC valide
205: * @access public
206: * @param string $mac Adresse MAC à vérifier
207: * @static
208: * @return boolean
209: */
210: public static function isMac($mac,$separator ='-')
211: {
212: $motif = '`^([[:xdigit:]]{2}\\'.$separator.'){5}[[:xdigit:]]{2}$`';
213: if (preg_match($motif, $mac))
214: return true;
215:
216: return false;
217: }
218:
219: /**
220: * Vérifie la syntaxe d'un mail.
221: * Gère également les mail locaux avec domaine simple
222: *
223: * @param string $mail Adresse email
224: * @param boolean $dot Un point obligatoire dans le domaine ?
225: * @return boolean
226: */
227: public static function isMail($mail, $dot = true)
228: {
229: if (function_exists('filter_var'))
230: {
231: if (filter_var($mail, FILTER_VALIDATE_EMAIL))
232: {
233: if ($dot)
234: {
235: $chaine = explode('@', $mail);
236: $domain = $chaine[1];
237: if (strpos($domain, '.'))
238: return true;
239:
240: return false;
241: }
242:
243: return true;
244: }
245: else
246: {
247: if(!$dot)
248: return self::checkmail($mail,false);
249: }
250: }
251: else
252: {
253: return self::checkmail($mail);
254: }
255:
256: return false;
257: }
258:
259: private static function checkmail($mail,$dot=true)
260: {
261: $atom = '[-a-z0-9!#$%&\'*+\\/=?^_`{|}~]'; // caractères autorisés avant l'arobase
262: $domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)'; // nom de domaine
263: $regex = '/^' . $atom . '+(\.' . $atom . '+)*@(' . $domain . '{1,63}\.)+' . $domain . '{2,63}$/i';
264: $regexNoDot = '/^' . $atom . '+(\.' . $atom . '+)*@(' . $domain . '{1,63})+' . $domain . '{2,63}$/i';
265: if (preg_match($regex, $mail))
266: return true;
267: if (!$dot && preg_match($regexNoDot, $mail))
268: return true;
269: }
270:
271: /**
272: * Vérifie si une chaine est complexe.
273: * Est considérée comme complexe une chaine d'au moins 6 caractères,
274: * une minuscule, une maj , un chiffre et un caractère spécial
275: * @param string $string
276: * @return boolean
277: */
278: public static function isComplex($string)
279: {
280: if (preg_match("`^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{6,}$`", $string))
281: return true;
282:
283: return false;
284: }
285:
286: /**
287: * Conversion de date au format Mysql
288: * @param string $date Date
289: * @param string $format Format de la date fournie
290: * @since 1.7.8
291: * @return string Date au format mysql Y-m-d ou false en cas d'erreur
292: */
293: public static function date2Mysql($date, $format)
294: {
295: $dt = DateTime::createFromFormat($format, $date);
296: if($dt)
297: return $dt->format("Y-m-d");
298:
299: return false;
300: }
301:
302: /**
303: * Convertit un datetime en format fr ou en
304: * @param string $datetime
305: * @param string $format Format de langue fr ou en
306: * @param boolean $short Date raccourcie (jjmm hhii) ou non
307: * @return array
308: */
309: public static function dateTime2Array($datetime, $format='fr', $short=false)
310: {
311: list($date, $heure) = explode(' ', $datetime);
312: list($y, $m, $d) = explode('-', $date);
313: list($h, $min, $s) = explode(':', $heure);
314: $tabRet = array();
315: switch ($format) {
316: case 'fr' : {
317: if ($short)
318: {
319: $tabRet[] = $d . '/' . $m;
320: $tabRet[] = $h . 'h' . $min;
321: }
322: else
323: {
324: $tabRet[] = $d . '/' . $m . '/' . $y;
325: $tabRet[] = $h . ':' . $min . ':' . $s;
326: }
327: break;
328: }
329:
330: case 'en' : {
331: if ($short)
332: {
333: $tabRet[] = $m . '/' . $d;
334: $tabRet[] = $h . 'h' . $min;
335: }
336: else
337: {
338: $tabRet[] = $m . '/' . $d . '/' . $y;
339: $tabRet[] = $h . ':' . $min . ':' . $s;
340: }
341: break;
342: }
343: }
344: return $tabRet;
345: }
346:
347: /**
348: * reduceDoubleSlashes
349: * Transforme les // en / sauf sur http://
350: * @param string $chaine
351: * @return string
352: */
353: public static function reduceDoubleSlashes($chaine)
354: {
355: return preg_replace("#(^|[^:])//+#", "\\1/", $chaine);
356: }
357:
358: /**
359: * Convertit une chaine de caractère en sa représentation hexadecimal
360: * @param string $str
361: * @return string
362: */
363: public function str2hex($str)
364: {
365: $retval = '';
366: $length = strlen($str);
367:
368: for($idx = 0; $idx < $length; $idx++)
369: $retval .= str_pad(base_convert(ord($str[$idx]), 10, 16), 2, '0', STR_PAD_LEFT);
370:
371: return $retval;
372: }
373:
374: /**
375: * Retourne une chaine en UTF8
376: * @param string $str Chaine à convertir
377: * @return string Chaine en UTF8
378: * @since 1.8.6
379: */
380: public function toUTF8($str)
381: {
382: $encoding = mb_detect_encoding($str, mb_detect_order(),true);
383: if($encoding != 'UTF-8')
384: {
385: if($encoding)
386: $str = mb_convert_encoding ($str, 'UTF-8', $encoding);
387: else
388: $str = mb_convert_encoding ($str, 'UTF-8');
389: }
390: return $str;
391: }
392:
393: }
394:
395: ?>
396: