source: branches/1.2/workflow/inc/class.utils.string.php @ 1349

Revision 1349, 19.1 KB checked in by niltonneto, 15 years ago (diff)

Ticket #561 - Inclusão do módulo Workflow faltante nessa versão.

  • Property svn:executable set to *
Line 
1<?php
2require_once('class.utils.php');
3/**
4 * Contains useful methods for string handling that extend standard PHP set and include new tools
5 * @author Carlos Eduardo Nogueira Gonçalves
6 * @author Marcos Pont
7 * @version 1.0
8 * @link http://workflow.celepar.parana/doc-workflow/classes/stringutils Complete reference
9 * @package Workflow
10 * @license http://www.gnu.org/copyleft/gpl.html GPL
11 */
12class StringUtils extends Utils
13{
14        /**
15         * Strips all blank  characters from the beginning and end of a string
16         * @param string $str
17         * @return result string
18         * @access public
19         */
20        function allTrim($str) {
21                return $this->stripBlank(trim($str));
22        }
23
24        /**
25         * Replace all blank characters
26         * @param string $str         
27         * @param string $replace replace string
28         * @return string result string   
29         * @access public
30         */
31        function stripBlank($str, $replace=' ') {
32                return ereg_replace("[[:blank:]]{1,}", $replace, $str);
33        }
34       
35        /**
36         * Return the first n chars of the string
37         * @param string $str base string
38         * @param int $chars number of chars to return 
39         * @return string result substring
40         * @access public
41         */
42        function left($str, $chars = 0) {
43                if (!$this->isInteger($chars)) {
44                        return $str;
45                } else if ($chars == 0) {
46                        return '';
47                } else {
48                        return substr($str, 0, $chars);
49                }
50        }
51       
52        /**
53         * Return the last n chars of the string
54         * @param string $str base string 
55         * @param int $chars  number of chars to return
56         * @return string result substring
57         * @access public
58         */
59        function right($str, $chars=0) {
60                if (!$this->isInteger($chars)) {
61                        return $str;
62                } else if ($chars == 0) {
63                        return '';
64                } else {
65                        return substr($str, strlen($str) - $chars, strlen($str)-1);
66                }
67        }
68       
69        /**
70         * Return parts of the current string
71         * @param string $str   base string 
72         * @param int   $startAt
73         * @param int   $chars
74         * @return string result substring
75         * @access public
76         */
77        function mid($str, $startAt=1, $chars=0) {
78                if (!$this->isInteger($chars)) {
79                        return $str;
80                } else if ($str == '' || $chars == 0) {
81                        return '';
82                } else if (($startAt + $chars) > strlen($str)) {
83                        return $str;
84                } else {
85                        if ($startAt == 0) $startAt = 1;
86                        return substr($str, $startAt-1, $chars);
87                }
88        }
89       
90        /**
91         * Returns the character at position 
92         * @param string $str reference string
93         * @param $index
94         * @return string string value of a variable
95         * @access public
96         */
97        function charAt($str, $index) {
98                if (!$this->isInteger($index)) {
99                        return '';
100                } else if ($str == '' || $index < 0 || $index >= strlen($str)) {
101                        return '';
102                } else {
103                        $strTranslated = strval($str);
104                        return $strTranslated{$index};
105                }
106        }
107        /**
108         * Search a string in another string
109         * @param string $str reference string 
110         * @param $sValue search string
111         * @param $caseSensitive caseSensitive true or false
112         * @return string position of  first occurrence of  sValue in str
113         * @access public
114         */
115        function match($str, $sValue, $caseSensitive=TRUE) {
116                if (!$caseSensitive) $sValue = strtolower($sValue);
117                if (strlen($sValue) == 0) {
118                        return FALSE;
119                } else {
120                        $pos = strpos($str, $sValue);
121                        return ($pos !== FALSE);
122                }
123        }
124        /**
125         * Return all string starts with the substring
126         * @param string $str referenfe string
127         * @param $slice
128         * @param bool $caseSensitive caseSensitive true or false
129         * @param bool $ignSpaces ignore spaces
130         * @return string
131         * @access public 
132         */
133        function startsWith($str, $slice, $caseSensitive=TRUE, $ignSpaces=TRUE) {
134                if (!$caseSensitive) {
135                        $strUsed = ($ignSpaces) ? ltrim(strtolower($str)) : strtolower($str);
136                        $sliceUsed = strtolower($slice);
137                } else {
138                        $strUsed = ($ignSpaces) ? ltrim($str) : $str;
139                        $sliceUsed = $slice;
140                }
141                return ($this->left($strUsed, strlen($sliceUsed)) == $sliceUsed);
142        }
143       
144        /**
145         * Return all string ends with the substring
146         * @param string $str
147         * @param $slice
148         * @param bool $caseSensitive caseSensitive true or false
149         * @param bool $ignSpaces ignore spaces
150         * @return string
151         * @access public 
152         */
153        function endsWith($str, $slice, $caseSensitive=TRUE, $ignSpaces=TRUE) {
154                if (!$caseSensitive) {
155                        $strUsed = ($ignSpaces) ? rtrim(strtolower($str)) : strtolower($str);
156                        $sliceUsed = strtolower($slice);
157                } else {
158                        $strUsed = ($ignSpaces) ? rtrim($str) : $str;
159                        $sliceUsed = $slice;
160                }
161                return ($this->right($strUsed, strlen($sliceUsed)) == $sliceUsed);
162        }
163       
164        /**
165         * Checks with the all characters of string is upper case
166         * @param string $str
167         * @return bool
168         * @access public   
169         */
170        function isAllUpper($str) {
171                return (preg_match("/[a-z]/", $str) !== FALSE);
172        }
173       
174        /**
175         * Checks with the all characters of string is lower case
176         * @param string $str
177         * @return bool
178         * @access public 
179         *
180         */
181        function isAllLower($str) {
182                return (preg_match("/[A-Z]/", $str) !== FALSE);
183        }
184       
185        /**
186         * Checks with the values is empty
187         * @param string $value
188         * @return bool
189         * @access public 
190         */
191        function isEmpty($value) {
192                $value = strval($value);
193                return (empty($value) && strlen($value) == 0);
194        }
195       
196        /**
197         * If the $values replace with the $replacement parameter
198         * @param mixed $value         
199         * @param mixed $replacement
200         * @return bool
201         * @access public 
202         */
203        function ifEmpty($value, $replacement) {
204                return (empty($value) ? $replacement : $value);
205        }
206
207        /**
208         * Concat two strings
209         * @param string $str first string
210         * @param string $concat second string
211         * @return result string
212         */
213        function concat($str, $concat) {
214                return $str . $concat;
215        }
216
217        /**
218         * Adds a prefix and suffix to a string
219         * @param string $str     reference string
220         * @param string $prefix  prefix string
221         * @param string $suffix  suffix string
222         * @return string result string
223         * @access public 
224         */
225        function surround($str, $prefix, $suffix) {
226                return $prefix . $str . $suffix;
227        }
228       
229        /**
230         * Insert a value in a determined  position in a string
231         * @param $str reference string
232         * @param $insValue value to insert
233         * @param $insPos insert position
234         * @return string
235         * @access public
236         */
237        function insert($str, $insValue = '', $insPos = 0) {
238                if (($insValue == '') || ($insPos < 0) || ($insPos > strlen($str))) {
239                        return $str;
240                } else if ($insPos == 0) {
241                        return $insValue . $str;
242                } else if ($insPos == strlen($str)) {
243                        return $str . $insValue;
244                } else {
245                        return $this->left($str, $insPos) . $insValue . $this->right($str, $insPos, strlen($str) - $insPos);
246                }
247        }
248
249        /**
250         * Replace all occurrences of search in haystack with replace
251         *
252         * @param string $str reference string
253         * @param string $from string to search
254         * @param string $to  string to replace
255         * @return mixed
256         * @access public
257         */
258        function replace($str, $from, $to) {
259                return str_replace($from, $to, $str);
260        }
261       
262        /**
263         * Replace the pattern with a parameter string
264         *
265         * @param string $str reference string
266         * @param string $pattern pattern to search
267         * @param string $replacement string to replace
268         * @return string 
269         * @access public
270         */
271        function regexReplace($str, $pattern, $replacement) {
272                if (empty($pattern))
273                        return $str;
274                $matches = array();
275        if (preg_match('!\W(\w+)$!s', $pattern, $matches) && (strpos($matches[1], 'e') !== FALSE))
276                        $pattern = substr($pattern, 0, -strlen($matches[1])) . str_replace('e', '', $matches[1]);
277                return preg_replace($pattern, $replacement, $str);
278        }
279       
280        /**
281         * Explode a string  in array of components
282         *
283         * @param string $str reference string
284         * @param string $sep separator
285         * @return array array of components
286         * @access public
287         */
288        function explode($str, $sep) {
289                $arr = explode($sep, $str);
290                return $arr;
291        }
292       
293        /**
294         * Join elements array in one string
295         * @param string $str reference string
296         * @param string $glue glue string
297         * @return string result string
298         * @access public
299         */
300        function implode($values, $glue) {
301                return implode($glue, (array)$values);
302        }
303
304        /**
305         * Encode the string with encodetype
306         *
307         * @param string $str reference string
308         * @param string $encodeType encode type: 'base64', 'utf8' ,'7bit' , '8bit' or 'quoted-printable'
309         * @param array  $params
310         * @return string encoded string
311         * @access public
312         */
313        function encode($str, $encodeType, $params=NULL) {
314                switch(strtolower($encodeType)) {
315                        case 'base64' :
316                                $encoded = chunk_split(base64_encode($str));
317                                break;
318                        case 'utf8' :
319                                $encoded = utf8_encode($str);
320                                break;
321                        case '7bit' :
322                        case '8bit' :
323                                $nl = $this->ifNull($params['nl'], "\n");
324                                $str = str_replace(array("\r\n", "\r"), array("\n", "\n"), $str);
325                                $encoded = str_replace("\n", $nl, $str);
326                                if (!$this->endsWith($encoded, $nl))
327                                        $encoded .= $nl;
328                                break;
329                        case 'quoted-printable' :
330                                static $qpChars;
331                                if (!isset($qpChars))
332                                        $qpChars = array_merge(array(64, 61, 46), range(0, 31), range(127, 255));
333                                $charset = $this->ifNull($params['charset'], 'iso-8859-1');
334                                $replace = array(' ' => '_');
335                                foreach ($qpChars as $char)
336                                        $replace[chr($char)] = '=' . strtoupper(dechex($char));
337                                return sprintf("=?%s?Q?%s=", $charset, strtr($str, $replace));
338                        default:
339                                $encoded = $str;
340                                break;
341                }
342                return $encoded;
343        }
344        /**
345         * Decode the string parameter with encodetype 
346         *
347         * @param string $str reference string
348         * @param string $encodetype 'base64', 'base64', 'quoted-printable'
349         * @return string decode string
350         * @access public
351         */
352        function decode($str, $encodeType) {
353                switch(strtolower($encodeType)) {
354                        case 'base64' :
355                                $decoded = base64_decode($str);
356                                break;
357                        case 'base64' :
358                                $decoded = utf8_decode($str);
359                                break;
360                        case 'quoted-printable' :
361                                $decoded = quoted_printable_decode($str);
362                                break;
363                        default :
364                                $decoded = $str;
365                                break;
366                }
367                return $decoded;
368        }
369       
370        /**
371         * Map
372         *
373         * @access public
374         */
375        function map() {
376                $argc = func_num_args();
377                $argv = func_get_args();
378                if ($argc == 0)
379                        return NULL;
380                $base = $argv[0];
381                for ($i=1,$s=sizeof($argv); $i<$s; $i+=2) {
382                        if (array_key_exists($i+1, $argv)) {
383                                if ($base == $argv[$i])
384                                        return $argv[$i+1];
385                        } else {
386                                return $argv[$i];
387                        }
388                }
389                return $base;
390        }
391       
392        /**
393         * Filter the selected strings 
394         *
395         * @param string $str string reference
396         * @param string $filtertype regex expression
397         * @param string $replaceStr string to replace
398         *
399         * @return string
400         * @access public
401         *
402         */
403        function filter($str, $filterType='alphanum', $replaceStr='') {
404                $replaceStr = strval($replaceStr);
405                switch ($filterType) {
406                        case 'alpha' :
407                                return (ereg_replace("[^a-zA-Z]", $replaceStr, $str));
408                        case 'alphalower' :
409                                return (ereg_replace("[^a-z]", $replaceStr, $str));
410                        case 'alphaupper' :
411                                return (ereg_replace("[^A-Z]", $replaceStr, $str));
412                        case 'num' :
413                                return (ereg_replace("[^0-9]", $replaceStr, $str));
414                        case 'alphanum' :
415                                return (ereg_replace("[^0-9a-zA-Z]", $replaceStr, $str));
416                        case 'htmlentities' :
417                                return (ereg_replace("&[[:alnum:]]{0,};", $replaceStr, $str));
418                        case 'blank' :
419                                return (ereg_replace("[[:blank:]]{1,}", $replaceStr, $str));
420                        default :
421                                return $str;
422                }
423        }
424
425        /**
426         * Escape special characters
427         *
428         * @param string $str reference string 
429         * @param string $conversionType 'html', 'htmlall' ,'url' ,'quotes', 'javascript' 'mail'
430         * @access public
431         * @return string
432         */
433        function escape($str, $conversionType='html') {
434                switch ($conversionType) {
435                        case 'html':
436                                return htmlspecialchars($str, ENT_QUOTES);
437                        case 'htmlall' :
438                                return htmlentities($str, ENT_QUOTES);
439                        case 'url' :
440                                return rawurlencode($str);
441                        case 'quotes' :
442                                return preg_replace("%(?<!\\\\)'%", "\\'", $str);
443                        case 'javascript' :
444                                $expressions = array(
445                                        "/(<scr)(ipt)/i" => "$1\"+\"$2", // quebrar tags "<script"
446                                        '/\\\\/' => '\\\\', // backslashes
447                                        '/\'/' => "\'", // single quotes
448                                        '/"/' => '\\"', // double quotes
449                                        "/\r/"=>'\\r', // caractere CR
450                                        "/\n/"=>'\\n', // caractere LF
451                                        "/\t/" => "\\t" // tabulaᅵᅵes
452                                );
453                                $str = str_replace("\\", "\\\\", $str);
454                                $str = preg_replace(array_keys($expressions), array_values($expressions), $str);
455                                return $str;
456                        case 'mail' :
457                                return str_replace(array('@', '.'), array(' at ', ' dot '), $str);
458                        default :
459                                return $str;
460                }
461        }
462
463    /**
464     * Camelize a string
465     *
466     * @param  string $str
467     * @return string camelized string
468     * @access public
469     */
470        function camelize($str) {
471                return preg_replace("/[_|\s]([a-z0-9])/e", "strtoupper('\\1')", strtolower($str));
472        }
473
474        /**
475         * Capitalize the parameter string
476         * @param string $str parameterstring
477         * @return string result string
478         * @access public
479         */
480        function capitalize($str) {
481                if (!empty($str)) {
482                        $w = preg_split("/\s+/", $str);
483                        for ($i=0, $s=sizeof($w); $i<$s; $i++) {
484                                if (empty($w[$i]))
485                                        continue;
486                                $f = strtoupper($w[$i][0]);
487                                $r = strtolower(substr($w[$i], 1));
488                                $w[$i] = $f . $r;
489                        }
490                        return implode(' ', $w);
491                }
492                return $str;
493        }
494       
495        /**
496         * Normalize the string
497         * @param string $str reference string
498         * @return string normalized string
499         * @access public
500         */
501        function normalize($str) {
502                $ts = array("/[ï¿œ-ï¿œ]/", "/ï¿œ/", "/ï¿œ/", "/[ï¿œ-ï¿œ]/", "/[ï¿œ-ï¿œ]/", "/ï¿œ/", "/ï¿œ/", "/[ï¿œ-ᅵᅵ]/", "/ï¿œ/", "/[ï¿œ-ï¿œ]/", "/ï¿œ/", "/ï¿œ/", "/[ï¿œ-ï¿œ]/", "/ï¿œ/", "/ï¿œ/", "/[ï¿œ-ï¿œ]/", "/[ï¿œ-ï¿œ]/", "/ï¿œ/", "/ï¿œ/", "/[ï¿œ-ᅵᅵ]/", "/ï¿œ/", "/[ï¿œ-ï¿œ]/", "/[ï¿œ-ï¿œ]/");
503                $tn = array("A", "AE", "C", "E", "I", "D", "N", "O", "X", "U", "Y", "ss", "a", "ae", "c", "e", "i", "d", "n", "o", "x", "u", "y");
504                return preg_replace($ts, $tn, $str);
505        }
506       
507        /**
508         * Cut before
509         * @param string $string
510         * @param string $token string to match
511         * @param bool
512         * @return string
513         * @access public
514         */
515        function cutBefore($string, $token, $caseSensitive=TRUE) {
516                if ($this->match($caseSensitive ? $string : strtolower($string), $token, $caseSensitive)) {
517                        return stristr($string, $token);
518                }
519                return $string;
520        }
521       
522        /**
523         * Cut last occurrence 
524         * @param string $string
525         * @param string $cutOff
526         * @param bool $caseSensitive
527         * @param bool
528         * @return string
529         * @access public
530         */
531        function cutLastOcurrence($string, $cutOff, $caseSensitive=TRUE) {
532                if (!$this->match($caseSensitive ? $string : strtolower($string), $cutOff, $caseSensitive))
533                        return $string;
534                else
535                        return strrev(substr(stristr(strrev($string), strrev($cutOff)),strlen($cutOff)));
536        }
537
538        /**
539         * Ident a string
540         * @param string $str string reference
541         * @access public
542         * @return string
543         */     
544        function indent($str, $nChars, $iChar=' ') {
545                if (!$this->isInteger($nChars) || $nChars < 1) {
546                        $nChars = 1;
547                }
548                return preg_replace('!^!m', str_repeat($iChar, $nChars), $str);
549        }
550
551        /**
552         * Truncate .....
553         * @param string $str reference string
554         * @param int $lenght
555         * @param string $truncSufix truncate sufix
556         * @param bool $forcebreak
557         * @return string 
558         * @access public
559         */
560        function truncate($str, $length, $truncSufix='...', $forceBreak=TRUE) {
561                if (!$this->isInteger($length) || $length < 1) {
562                        return '';
563                } else {
564                        if (strlen($str) > $length) {
565                                $length -= strlen($truncSufix);
566                        if (!$forceBreak)
567                        $str = preg_replace('/\s+?(\S+)?$/', '', substr($str, 0, $length+1));
568                                return substr($str, 0, $length) . $truncSufix;
569                        } else {
570                                return $str;
571                        }
572                }
573        }
574       
575        /**
576         * Insert Char in string
577         * @param $str reference string
578         * @param bool $stringEmpty
579         * @param string $char
580         * @return string
581         * @access public
582         */
583        function insertChar($str, $char = ' ', $stripEmpty = TRUE) {
584                if ($stripEmpty) {
585                        $strChars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
586                } else {
587                        $strChars = preg_split('//', $str, -1);
588                }
589                return implode($char, $strChars);
590        }
591       
592        /**
593         * Wrap line
594         * @param string $str reference string   
595         * @param int $num num of line to wrap
596         * @param string $breakstring 
597         * @return string
598         * @access public
599         */
600        function wrapLine($str, $num, $breakString="\n") {
601                $line = '';
602                $processed = '';
603                $token = strtok($str, ' ');
604                while($token) {
605                        if (strlen($line) + strlen($token) < ($num + 2)) {
606                                $line .= " $token";
607                        } else {
608                                $processed .= "$line$breakString";
609                                $line = $token;
610                        }
611                        $token = strtok(' ');
612                }
613                $processed .= $line;
614                $processed = trim($processed);
615                return $processed;
616        }
617
618        /**
619         * Wrap  ....
620         *
621         * @param $str reference string
622         * @param string $breakString separator
623         * @return string  $processed 
624         * @access public
625         */
626        function wrap($str, $num, $breakString="\n") {
627                $str = ereg_replace("([^\r\n])\r\n([^\r\n])", "\\1 \\2", $str);
628                $str = ereg_replace("[\r\n]*\r\n[\r\n]*", "\r\n\r\n", $str);
629                $str = ereg_replace("[ ]* [ ]*", ' ', $str);
630                $str = stripslashes($str);
631                $processed = '';
632                $paragraphs = explode("\n", $str);
633                for ($i=0; $i<sizeof($paragraphs); $i++) {
634                        $processed .= $this->wrapLine($paragraphs[$i], $num, $breakString) . $breakString;
635                }
636                $processed = trim($processed);
637                return $processed;
638        }
639       
640        /**
641         * Add line numbers
642         *
643         * @param string $str reference string 
644         * @param string $start character to start 
645         * @param string $indent indent size 
646         * @param string $afternumberChar char to place after number 
647         * @return string $processed  result string
648         * @access public
649         */
650        function addLineNumbers(&$str, $start = 1, $indent = 3, $afterNumberChar = ':', $glue='\n') {
651                // divide a string em linhas de um array
652                $line = explode("\n", $str);
653                $size = sizeof($line);
654                // calcula a largura maxima da numeraçao de acordo com o numero de linhas
655                $width = strlen((string)($start + $size -1));
656                $indent = max($width, $indent);
657                // gera a numeraᅵᅵo de linhas da string
658                for ($i = 0; $i < $size; $i++) {
659                        $line[$i] = str_pad((string)($i + $start), $indent, ' ', STR_PAD_LEFT) . $afterNumberChar . ' ' . trim($line[$i]);
660                }
661                return implode($glue, $line);
662        }
663
664        /**
665         * Count Chars
666         * @param string $str  reference string
667         * @param bool $includeSpaces spaces too
668         * @return int number of chars
669         * @access public
670         */
671        function countChars($str, $includeSpaces = FALSE) {
672                if ($includeSpaces) {
673                        return strlen($str);
674                } else {
675                        $match = array();
676                        return preg_match_all('/[^\s]/', $str, $match);
677                }
678        }
679
680        /**
681         * Count Words in a string
682         * @param string $str reference string
683         * @return mixed array or string
684         * @access public
685         */
686        function countWords($str) {
687                return str_word_count($str);
688        }
689
690        /**
691         * Count Sentences in a string
692         * @param string $str reference string
693         * @return mixed number of sentences
694         * @access public
695         */
696        function countSentences($str) {
697                $matches = array();
698                return preg_match_all('/[^\s]\.(?!\w)/', $str, $matches);
699        }
700
701        /**
702         * Count Paragraphs in a string
703         * @param string $str reference string
704         * @return int number of paragraphs
705         * @access public
706         */
707        function countParagraphs($str) {
708                return count(preg_split('/[\r\n]+/', $str));
709        }
710       
711        /**
712         * Create a random string
713         *
714         * @param mixed $size size of the string 
715         * @param bool $upper upper case permitted
716         * @param bool $digit digits included
717         * @return string result string
718         * @access public
719         */
720        function randomString($size, $upper=TRUE, $digit=TRUE) {
721                $pSize = max(1, $size);
722                $start = $digit ? 48 : 65;
723                $end = 122;
724                $result = '';
725                while (strlen($result) < $size) {
726                        $random = $this->randomize($start, $end);
727                        if (($digit && $random >= 48 && $random <= 57) ||
728                                ($upper && $random >= 65 && $random <= 90) ||
729                                ($random >= 97 && $random <= 122)) {
730                                $result .= chr($random);
731                        }
732                }
733                return $result;
734        }
735}
736?>
Note: See TracBrowser for help on using the repository browser.