3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Stdlib\StringWrapper;
12 use Zend\Stdlib\Exception;
14 class MbString extends AbstractStringWrapper
17 * List of supported character sets (upper case)
20 * @link http://php.net/manual/mbstring.supported-encodings.php
22 protected static $encodings = null;
25 * Get a list of supported character encodings
29 public static function getSupportedEncodings()
31 if (static::$encodings === null) {
32 static::$encodings = array_map('strtoupper', mb_list_encodings());
34 // FIXME: Converting € (UTF-8) to ISO-8859-16 gives a wrong result
35 $indexIso885916 = array_search('ISO-8859-16', static::$encodings, true);
36 if ($indexIso885916 !== false) {
37 unset(static::$encodings[$indexIso885916]);
41 return static::$encodings;
47 * @throws Exception\ExtensionNotLoadedException
49 public function __construct()
51 if (! extension_loaded('mbstring')) {
52 throw new Exception\ExtensionNotLoadedException(
53 'PHP extension "mbstring" is required for this wrapper'
59 * Returns the length of the given string
64 public function strlen($str)
66 return mb_strlen($str, $this->getEncoding());
70 * Returns the portion of string specified by the start and length parameters
74 * @param int|null $length
75 * @return string|false
77 public function substr($str, $offset = 0, $length = null)
79 return mb_substr($str, $offset, $length, $this->getEncoding());
83 * Find the position of the first occurrence of a substring in a string
85 * @param string $haystack
86 * @param string $needle
90 public function strpos($haystack, $needle, $offset = 0)
92 return mb_strpos($haystack, $needle, $offset, $this->getEncoding());
96 * Convert a string from defined encoding to the defined convert encoding
99 * @param bool $reverse
100 * @return string|false
102 public function convert($str, $reverse = false)
104 $encoding = $this->getEncoding();
105 $convertEncoding = $this->getConvertEncoding();
107 if ($convertEncoding === null) {
108 throw new Exception\LogicException(
109 'No convert encoding defined'
113 if ($encoding === $convertEncoding) {
117 $fromEncoding = $reverse ? $convertEncoding : $encoding;
118 $toEncoding = $reverse ? $encoding : $convertEncoding;
119 return mb_convert_encoding($str, $toEncoding, $fromEncoding);