[ Index ]
 

Code source de Horde 3.1.3

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

/lib/Horde/ -> String.php (source)

   1  <?php
   2  
   3  $GLOBALS['_HORDE_STRING_CHARSET'] = 'iso-8859-1';
   4  
   5  /**
   6   * The String:: class provides static methods for charset and locale safe
   7   * string manipulation.
   8   *
   9   * $Horde: framework/Util/String.php,v 1.43.6.13 2006/03/13 09:46:07 jan Exp $
  10   *
  11   * Copyright 2003-2006 Jan Schneider <jan@horde.org>
  12   *
  13   * See the enclosed file COPYING for license information (LGPL). If you
  14   * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
  15   *
  16   * @author  Jan Schneider <jan@horde.org>
  17   * @since   Horde 3.0
  18   * @package Horde_Util
  19   */
  20  class String {
  21  
  22      /**
  23       * Caches the result of extension_loaded() calls.
  24       *
  25       * @param string $ext  The extension name.
  26       *
  27       * @return boolean  Is the extension loaded?
  28       *
  29       * @see Util::extensionExists()
  30       */
  31      function extensionExists($ext)
  32      {
  33          static $cache = array();
  34  
  35          if (!isset($cache[$ext])) {
  36              $cache[$ext] = extension_loaded($ext);
  37          }
  38  
  39          return $cache[$ext];
  40      }
  41  
  42      /**
  43       * Sets a default charset that the String:: methods will use if none is
  44       * explicitely specified.
  45       *
  46       * @param string $charset  The charset to use as the default one.
  47       */
  48      function setDefaultCharset($charset)
  49      {
  50          $GLOBALS['_HORDE_STRING_CHARSET'] = $charset;
  51          if (String::extensionExists('mbstring') &&
  52              function_exists('mb_regex_encoding')) {
  53              @mb_regex_encoding($charset);
  54          }
  55      }
  56  
  57      /**
  58       * Converts a string from one charset to another.
  59       *
  60       * Works only if either the iconv or the mbstring extension
  61       * are present and best if both are available.
  62       * The original string is returned if conversion failed or none
  63       * of the extensions were available.
  64       *
  65       * @param mixed $input  The data to be converted. If $input is an an array,
  66       *                      the array's values get converted recursively.
  67       * @param string $from  The string's current charset.
  68       * @param string $to    The charset to convert the string to. If not
  69       *                      specified, the global variable
  70       *                      $_HORDE_STRING_CHARSET will be used.
  71       *
  72       * @return string  The converted string.
  73       */
  74      function convertCharset($input, $from, $to = null)
  75      {
  76          /* Get the user's default character set if none passed in. */
  77          if (is_null($to)) {
  78              $to = $GLOBALS['_HORDE_STRING_CHARSET'];
  79          }
  80  
  81          /* If the from and to character sets are identical, return now. */
  82          $from = String::lower($from);
  83          $to = String::lower($to);
  84          if ($from == $to) {
  85              return $input;
  86          }
  87  
  88          if (is_array($input)) {
  89              $tmp = array();
  90              foreach ($input as $key => $val) {
  91                  $tmp[String::_convertCharset($key, $from, $to)] = String::convertCharset($val, $from, $to);
  92              }
  93              return $tmp;
  94          }
  95          if (is_object($input)) {
  96              $vars = get_object_vars($input);
  97              foreach ($vars as $key => $val) {
  98                  $input->$key = String::convertCharset($val, $from, $to);
  99              }
 100              return $input;
 101          }
 102  
 103          if (!is_string($input)) {
 104              return $input;
 105          }
 106  
 107          return String::_convertCharset($input, $from, $to);
 108      }
 109  
 110      /**
 111       * Internal function used to do charset conversion.
 112       *
 113       * @access private
 114       *
 115       * @param mixed $input  See String::convertCharset().
 116       * @param string $from  See String::convertCharset().
 117       * @param string $to    See String::convertCharset().
 118       *
 119       * @return string  The converted string.
 120       */
 121      function _convertCharset($input, $from, $to)
 122      {
 123          $output = '';
 124  
 125          /* Use utf8_[en|de]code() if possible. */
 126          $from_check = (($from == 'iso-8859-1') || ($from == 'us-ascii'));
 127          if ($from_check && ($to == 'utf-8')) {
 128              return utf8_encode($input);
 129          }
 130  
 131          $to_check = (($to == 'iso-8859-1') || ($to == 'us-ascii'));
 132          if (($from == 'utf-8') && $to_check) {
 133              return utf8_decode($input);
 134          }
 135  
 136          /* First try iconv with transliteration. */
 137          if (($from != 'utf7-imap') &&
 138              ($to != 'utf7-imap') &&
 139              String::extensionExists('iconv')) {
 140              /* We need to tack an extra character temporarily because
 141               * of a bug in iconv() if the last character is not a 7
 142               * bit ASCII character. */
 143              ini_set('track_errors', 1);
 144              $output = @iconv($from, $to . '//TRANSLIT', $input . 'x');
 145              $output = (isset($php_errormsg)) ? false :  String::substr($output, 0, -1, $to);
 146              ini_restore('track_errors');
 147          }
 148  
 149          /* Next try mbstring. */
 150          if (!$output && String::extensionExists('mbstring')) {
 151              $output = @mb_convert_encoding($input, $to, $from);
 152          }
 153  
 154          /* At last try imap_utf7_[en|de]code if appropriate. */
 155          if (!$output && String::extensionExists('imap')) {
 156              if ($from_check && ($to == 'utf7-imap')) {
 157                  return @imap_utf7_encode($input);
 158              }
 159              if (($from == 'utf7-imap') && $to_check) {
 160                  return @imap_utf7_decode($input);
 161              }
 162          }
 163  
 164          return (!$output) ? $input : $output;
 165      }
 166  
 167      /**
 168       * Makes a string lowercase.
 169       *
 170       * @param string  $string   The string to be converted.
 171       * @param boolean $locale   If true the string will be converted based on a
 172       *                          given charset, locale independent else.
 173       * @param string  $charset  If $locale is true, the charset to use when
 174       *                          converting. If not provided the current charset.
 175       *
 176       * @return string  The string with lowercase characters
 177       */
 178      function lower($string, $locale = false, $charset = null)
 179      {
 180          static $lowers;
 181  
 182          if ($locale) {
 183              /* The existence of mb_strtolower() depends on the platform. */
 184              if (String::extensionExists('mbstring') &&
 185                  function_exists('mb_strtolower')) {
 186                  if (is_null($charset)) {
 187                      $charset = $GLOBALS['_HORDE_STRING_CHARSET'];
 188                  }
 189                  $ret = @mb_strtolower($string, $charset);
 190                  if (!empty($ret)) {
 191                      return $ret;
 192                  }
 193              }
 194              return strtolower($string);
 195          }
 196  
 197          if (!isset($lowers)) {
 198              $lowers = array();
 199          }
 200          if (!isset($lowers[$string])) {
 201              $language = setlocale(LC_CTYPE, 0);
 202              setlocale(LC_CTYPE, 'en_US');
 203              $lowers[$string] = strtolower($string);
 204              setlocale(LC_CTYPE, $language);
 205          }
 206  
 207          return $lowers[$string];
 208      }
 209  
 210      /**
 211       * Makes a string uppercase.
 212       *
 213       * @param string  $string   The string to be converted.
 214       * @param boolean $locale   If true the string will be converted based on a
 215       *                          given charset, locale independent else.
 216       * @param string  $charset  If $locale is true, the charset to use when
 217       *                          converting. If not provided the current charset.
 218       *
 219       * @return string  The string with uppercase characters
 220       */
 221      function upper($string, $locale = false, $charset = null)
 222      {
 223          static $uppers;
 224  
 225          if ($locale) {
 226              /* The existence of mb_strtoupper() depends on the
 227               * platform. */
 228              if (function_exists('mb_strtoupper')) {
 229                  if (is_null($charset)) {
 230                      $charset = $GLOBALS['_HORDE_STRING_CHARSET'];
 231                  }
 232                  $ret = @mb_strtoupper($string, $charset);
 233                  if (!empty($ret)) {
 234                      return $ret;
 235                  }
 236              }
 237              return strtoupper($string);
 238          }
 239  
 240          if (!isset($uppers)) {
 241              $uppers = array();
 242          }
 243          if (!isset($uppers[$string])) {
 244              $language = setlocale(LC_CTYPE, 0);
 245              setlocale(LC_CTYPE, 'en_US');
 246              $uppers[$string] = strtoupper($string);
 247              setlocale(LC_CTYPE, $language);
 248          }
 249  
 250          return $uppers[$string];
 251      }
 252  
 253      /**
 254       * Returns a string with the first letter capitalized if it is
 255       * alphabetic.
 256       *
 257       * @param string  $string   The string to be capitalized.
 258       * @param boolean $locale   If true the string will be converted based on a
 259       *                          given charset, locale independent else.
 260       * @param string  $charset  The charset to use, defaults to current charset.
 261       *
 262       * @return string  The capitalized string.
 263       */
 264      function ucfirst($string, $locale = false, $charset = null)
 265      {
 266          if ($locale) {
 267              $first = String::substr($string, 0, 1, $charset);
 268              if (String::isAlpha($first, $charset)) {
 269                  $string = String::upper($first, true, $charset) . String::substr($string, 1, null, $charset);
 270              }
 271          } else {
 272              $string = String::upper(substr($string, 0, 1), false) . substr($string, 1);
 273          }
 274          return $string;
 275      }
 276  
 277      /**
 278       * Returns part of a string.
 279       *
 280       * @param string $string   The string to be converted.
 281       * @param integer $start   The part's start position, zero based.
 282       * @param integer $length  The part's length.
 283       * @param string $charset  The charset to use when calculating the part's
 284       *                         position and length, defaults to current
 285       *                         charset.
 286       *
 287       * @return string  The string's part.
 288       */
 289      function substr($string, $start, $length = null, $charset = null)
 290      {
 291          if (String::extensionExists('mbstring')) {
 292              if (is_null($charset)) {
 293                  $charset = $GLOBALS['_HORDE_STRING_CHARSET'];
 294              }
 295              if (is_null($length)) {
 296                  $length = String::length($string, $charset);
 297              }
 298              $ret = @mb_substr($string, $start, $length, $charset);
 299              if (!empty($ret)) {
 300                  return $ret;
 301              }
 302          }
 303          if (is_null($length)) {
 304              $length = String::length($string);
 305          }
 306          return substr($string, $start, $length);
 307      }
 308  
 309      /**
 310       * Returns the character (not byte) length of a string.
 311       *
 312       * @param string $string  The string to return the length of.
 313       * @param string $charset The charset to use when calculating the string's
 314       *                        length.
 315       *
 316       * @return string  The string's part.
 317       */
 318      function length($string, $charset = null)
 319      {
 320          if (is_null($charset)) {
 321              $charset = $GLOBALS['_HORDE_STRING_CHARSET'];
 322          }
 323          $charset = String::lower($charset);
 324          if ($charset == 'utf-8' || $charset == 'utf8') {
 325              return strlen(utf8_decode($string));
 326          }
 327          if (String::extensionExists('mbstring')) {
 328              $ret = @mb_strlen($string, $charset);
 329              if (!empty($ret)) {
 330                  return $ret;
 331              }
 332          }
 333          return strlen($string);
 334      }
 335  
 336      /**
 337       * Returns the numeric position of the first occurrence of $needle
 338       * in the $haystack string.
 339       *
 340       * @param string $haystack  The string to search through.
 341       * @param string $needle    The string to search for.
 342       * @param integer $offset   Allows to specify which character in haystack
 343       *                          to start searching.
 344       * @param string $charset   The charset to use when searching for the
 345       *                          $needle string.
 346       *
 347       * @return integer  The position of first occurrence.
 348       */
 349      function pos($haystack, $needle, $offset = 0, $charset = null)
 350      {
 351          if (String::extensionExists('mbstring')) {
 352              if (is_null($charset)) {
 353                  $charset = $GLOBALS['_HORDE_STRING_CHARSET'];
 354              }
 355              ini_set('track_errors', 1);
 356              $ret = @mb_strpos($haystack, $needle, $offset, $charset);
 357              ini_restore('track_errors');
 358              if (!isset($php_errormsg)) {
 359                  return $ret;
 360              }
 361          }
 362          return strpos($haystack, $needle, $offset);
 363      }
 364  
 365      /**
 366       * Returns a string padded to a certain length with another string.
 367       *
 368       * This method behaves exactly like str_pad but is multibyte safe.
 369       *
 370       * @param string $input    The string to be padded.
 371       * @param integer $length  The length of the resulting string.
 372       * @param string $pad      The string to pad the input string with. Must
 373       *                         be in the same charset like the input string.
 374       * @param const $type      The padding type. One of STR_PAD_LEFT,
 375       *                         STR_PAD_RIGHT, or STR_PAD_BOTH.
 376       * @param string $charset  The charset of the input and the padding
 377       *                         strings.
 378       *
 379       * @return string  The padded string.
 380       */
 381      function pad($input, $length, $pad = ' ', $type = STR_PAD_RIGHT,
 382                   $charset = null)
 383      {
 384          $mb_length = String::length($input, $charset);
 385          $sb_length = strlen($input);
 386          $pad_length = String::length($pad, $charset);
 387  
 388          /* Return if we already have the length. */
 389          if ($mb_length >= $length) {
 390              return $input;
 391          }
 392  
 393          /* Shortcut for single byte strings. */
 394          if ($mb_length == $sb_length && $pad_length == strlen($pad)) {
 395              return str_pad($input, $length, $pad, $type);
 396          }
 397  
 398          switch ($type) {
 399          case STR_PAD_LEFT:
 400              $left = $length - $mb_length;
 401              $output = String::substr(str_repeat($pad, ceil($left / $pad_length)), 0, $left, $charset) . $input;
 402              break;
 403          case STR_PAD_BOTH:
 404              $left = floor(($length - $mb_length) / 2);
 405              $right = ceil(($length - $mb_length) / 2);
 406              $output = String::substr(str_repeat($pad, ceil($left / $pad_length)), 0, $left, $charset) .
 407                  $input .
 408                  String::substr(str_repeat($pad, ceil($right / $pad_length)), 0, $right, $charset);
 409              break;
 410          case STR_PAD_RIGHT:
 411              $right = $length - $mb_length;
 412              $output = $input . String::substr(str_repeat($pad, ceil($right / $pad_length)), 0, $right, $charset);
 413              break;
 414          }
 415  
 416          return $output;
 417      }
 418  
 419      /**
 420       * Wraps the text of a message.
 421       *
 422       * @todo Make multibyte-save.
 423       *
 424       * @param string $text        String containing the text to wrap.
 425       * @param integer $length     Wrap $text at this number of characters.
 426       * @param string $break_char  Character(s) to use when breaking lines.
 427       * @param string $charset     Character set to use when breaking lines.
 428       * @param boolean $quote      Ignore lines that are wrapped with the '>'
 429       *                            character (RFC 2646)? If true, we don't
 430       *                            remove any padding whitespace at the end of
 431       *                            the string.
 432       *
 433       * @return string  String containing the wrapped text.
 434       */
 435      function wrap($text, $length = 80, $break_char = "\n", $charset = null,
 436                    $quote = false)
 437      {
 438          $paragraphs = array();
 439  
 440          foreach (preg_split('/\r?\n/', $text) as $input) {
 441              if ($quote && (strpos($input, '>') === 0)) {
 442                  $line = $input;
 443              } else {
 444                  /* We need to handle the Usenet-style signature line
 445                   * separately; since the space after the two dashes is
 446                   * REQUIRED, we don't want to trim the line. */
 447                  if ($input != '-- ') {
 448                      $input = rtrim($input);
 449                  }
 450                  $line = wordwrap($input, $length, $break_char);
 451              }
 452  
 453              $paragraphs[] = $line;
 454          }
 455  
 456          return implode($break_char, $paragraphs);
 457      }
 458  
 459      /**
 460       * Returns true if the every character in the parameter is an
 461       * alphabetic character. This method doesn't work with any charset
 462       * other than the current charset yet.
 463       *
 464       * @param $string   The string to test.
 465       * @param $charset  The charset to use when testing the string.
 466       *
 467       * @return boolean  True if the parameter was alphabetic only.
 468       */
 469      function isAlpha($string, $charset = null)
 470      {
 471          if (String::extensionExists('mbstring')) {
 472              $old_charset = mb_regex_encoding();
 473              if ($charset != $old_charset) {
 474                  @mb_regex_encoding($charset);
 475              }
 476              $alpha = !mb_ereg_match('[^[:alpha:]]', $string);
 477              if ($charset != $old_charset) {
 478                  @mb_regex_encoding($old_charset);
 479              }
 480              return $alpha;
 481          }
 482  
 483          return ctype_alpha($string);
 484      }
 485  
 486      /**
 487       * Returns true if every character in the parameter is a lowercase
 488       * letter in the current locale.
 489       *
 490       * @param $string   The string to test.
 491       * @param $charset  The charset to use when testing the string.
 492       *
 493       * @return boolean  True if the parameter was lowercase.
 494       */
 495      function isLower($string, $charset = null)
 496      {
 497          return ((String::lower($string, true, $charset) === $string) &&
 498                  String::isAlpha($string, $charset));
 499      }
 500  
 501      /**
 502       * Returns true if every character in the parameter is an
 503       * uppercase letter in the current locale.
 504       *
 505       * @param string $string   The string to test.
 506       * @param string $charset  The charset to use when testing the string.
 507       *
 508       * @return boolean  True if the parameter was uppercase.
 509       */
 510      function isUpper($string, $charset = null)
 511      {
 512          return ((String::upper($string, true, $charset) === $string) &&
 513                  String::isAlpha($string, $charset));
 514      }
 515  
 516      /**
 517       * Performs a multibyte safe regex match search on the text provided.
 518       *
 519       * @since Horde 3.1
 520       *
 521       * @param string $text     The text to search.
 522       * @param array $regex     The regular expressions to use, without perl
 523       *                         regex delimiters (e.g. '/' or '|').
 524       * @param string $charset  The character set of the text.
 525       *
 526       * @return array  The matches array from the first regex that matches.
 527       */
 528      function regexMatch($text, $regex, $charset = null)
 529      {
 530          if (!empty($charset)) {
 531              $regex = String::convertCharset($regex, $charset, 'utf-8');
 532              $text = String::convertCharset($text, $charset, 'utf-8');
 533          }
 534  
 535          $matches = array();
 536          foreach ($regex as $val) {
 537              if (preg_match('/' . $val . '/u', $text, $matches)) {
 538                  break;
 539              }
 540          }
 541  
 542          if (!empty($charset)) {
 543              $matches = String::convertCharset($matches, 'utf-8', $charset);
 544          }
 545  
 546          return $matches;
 547      }
 548  
 549  }


Généré le : Sun Feb 25 18:01:28 2007 par Balluche grâce à PHPXref 0.7