Overview

Namespaces

  • None
  • PHP
  • Pry
    • Auth
      • Interfaces
    • Config
    • Controller
    • Date
    • Db
    • Feed
      • Abstracts
      • Writers
    • File
      • Decorator
    • Form
      • Element
    • Image
    • Log
      • Writer
    • Net
      • Exception
    • Session
    • Util
    • Validate
      • Validator
    • View

Classes

  • Bench
  • CommandLineBuilder
  • Pagination
  • Registry
  • Strings
  • Token
  • UserAgent

Exceptions

  • ExceptionHandler
  • Overview
  • Namespace
  • Class
  • Tree
  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:  */
 12: 
 13: namespace Pry\Util;
 14: 
 15: /**
 16:  * Classe String
 17:  *
 18:  * Class de gestion de string
 19:  *
 20:  * @category Pry
 21:  * @package Util
 22:  * @version 1.9.0
 23:  * @author Olivier ROGER <oroger.fr>
 24:  *  
 25:  */
 26: class Strings
 27: {
 28: 
 29:     /**
 30:      * Ajout de slashe. Ajoute des slashes si magiquotes desactivé
 31:      * @access public
 32:      * @param string $chaine Chaine à traiter
 33:      * @static
 34:      * @return string Chaine complétée par des /
 35:      */
 36:     public static function slashes($chaine)
 37:     {
 38:         if (!get_magic_quotes_gpc())
 39:             $chaine = addslashes($chaine);
 40: 
 41:         return $chaine;
 42:     }
 43: 
 44:     /**
 45:      * Nettoyage de chaine. Reécrit une chaine pour supprimer espace et caractère spéciaux, accentués ...
 46:      * @access public
 47:      * @param string $titre Chaine à traiter
 48:      * @param string $delimiter Charactère délimiteur
 49:      * @static
 50:      * @return string chaine modifiée
 51:      * */
 52:     public static function clean($string, $delimiter = "_")
 53:     {
 54:         //Transformation des apostrophe en espace pour avoir :
 55:         // c'est = "c-est" et non pas "cest"
 56:         $string = str_replace("'", ' ', $string);
 57: 
 58:         $cleanStr = iconv('UTF-8', 'ASCII//TRANSLIT', $string); //Suppression accent
 59:         $cleanStr = trim(strtolower($cleanStr));
 60:         $cleanStr = preg_replace("/[^a-z0-9\/_|+ -]/", '', $cleanStr);
 61:         $cleanStr = preg_replace("/[\/_|+ -]+/", $delimiter, $cleanStr);
 62: 
 63:         return $cleanStr;
 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($string, 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:         {
317:             case 'fr' :
318:                 {
319:                     if ($short)
320:                     {
321:                         $tabRet[] = $d . '/' . $m;
322:                         $tabRet[] = $h . 'h' . $min;
323:                     }
324:                     else
325:                     {
326:                         $tabRet[] = $d . '/' . $m . '/' . $y;
327:                         $tabRet[] = $h . ':' . $min . ':' . $s;
328:                     }
329:                     break;
330:                 }
331: 
332:             case 'en' :
333:                 {
334:                     if ($short)
335:                     {
336:                         $tabRet[] = $m . '/' . $d;
337:                         $tabRet[] = $h . 'h' . $min;
338:                     }
339:                     else
340:                     {
341:                         $tabRet[] = $m . '/' . $d . '/' . $y;
342:                         $tabRet[] = $h . ':' . $min . ':' . $s;
343:                     }
344:                     break;
345:                 }
346:         }
347:         return $tabRet;
348:     }
349: 
350:     /**
351:      * reduceDoubleSlashes
352:      * Transforme les // en / sauf sur http://
353:      * @param string $chaine
354:      * @return string
355:      */
356:     public static function reduceDoubleSlashes($chaine)
357:     {
358:         return preg_replace("#(^|[^:])//+#", "\\1/", $chaine);
359:     }
360: 
361:     /**
362:      * Convertit une chaine de caractère en sa représentation hexadecimal
363:      * @param string $str
364:      * @return string 
365:      */
366:     public function str2hex($str)
367:     {
368:         $retval = '';
369:         $length = strlen($str);
370: 
371:         for ($idx = 0; $idx < $length; $idx++)
372:             $retval .= str_pad(base_convert(ord($str[$idx]), 10, 16), 2, '0', STR_PAD_LEFT);
373: 
374:         return $retval;
375:     }
376: 
377:     /**
378:      * Retourne une chaine en UTF8
379:      * @param string $str Chaine à convertir
380:      * @return string Chaine en UTF8
381:      * @since 1.8.6 
382:      */
383:     public function toUTF8($str)
384:     {
385:         $encoding = mb_detect_encoding($str, mb_detect_order(), true);
386:         if ($encoding != 'UTF-8')
387:         {
388:             if ($encoding)
389:                 $str = mb_convert_encoding($str, 'UTF-8', $encoding);
390:             else
391:                 $str = mb_convert_encoding($str, 'UTF-8');
392:         }
393:         return $str;
394:     }
395: 
396: }
Pry API documentation generated by ApiGen 2.8.0