| 1 |
<?php |
| 2 |
|
| 3 |
namespace Box\Spout\Common\Helper; |
| 4 |
|
| 5 |
/** |
| 6 |
* Class StringHelper |
| 7 |
* This class provides helper functions to work with strings and multibyte strings. |
| 8 |
* |
| 9 |
* @codeCoverageIgnore |
| 10 |
* |
| 11 |
* @package Box\Spout\Common\Helper |
| 12 |
*/ |
| 13 |
class StringHelper |
| 14 |
{ |
| 15 |
/** @var bool Whether the mbstring extension is loaded */ |
| 16 |
protected $hasMbstringSupport; |
| 17 |
|
| 18 |
/** |
| 19 |
* |
| 20 |
*/ |
| 21 |
public function __construct() |
| 22 |
{ |
| 23 |
$this->hasMbstringSupport = extension_loaded('mbstring'); |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Returns the length of the given string. |
| 28 |
* It uses the multi-bytes function is available. |
| 29 |
* @see strlen |
| 30 |
* @see mb_strlen |
| 31 |
* |
| 32 |
* @param string $string |
| 33 |
* @return int |
| 34 |
*/ |
| 35 |
public function getStringLength($string) |
| 36 |
{ |
| 37 |
return $this->hasMbstringSupport ? mb_strlen($string) : strlen($string); |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Returns the position of the first occurrence of the given character/substring within the given string. |
| 42 |
* It uses the multi-bytes function is available. |
| 43 |
* @see strpos |
| 44 |
* @see mb_strpos |
| 45 |
* |
| 46 |
* @param string $char Needle |
| 47 |
* @param string $string Haystack |
| 48 |
* @return int Char/substring's first occurrence position within the string if found (starts at 0) or -1 if not found |
| 49 |
*/ |
| 50 |
public function getCharFirstOccurrencePosition($char, $string) |
| 51 |
{ |
| 52 |
$position = $this->hasMbstringSupport ? mb_strpos($string, $char) : strpos($string, $char); |
| 53 |
return ($position !== false) ? $position : -1; |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Returns the position of the last occurrence of the given character/substring within the given string. |
| 58 |
* It uses the multi-bytes function is available. |
| 59 |
* @see strrpos |
| 60 |
* @see mb_strrpos |
| 61 |
* |
| 62 |
* @param string $char Needle |
| 63 |
* @param string $string Haystack |
| 64 |
* @return int Char/substring's last occurrence position within the string if found (starts at 0) or -1 if not found |
| 65 |
*/ |
| 66 |
public function getCharLastOccurrencePosition($char, $string) |
| 67 |
{ |
| 68 |
$position = $this->hasMbstringSupport ? mb_strrpos($string, $char) : strrpos($string, $char); |
| 69 |
return ($position !== false) ? $position : -1; |
| 70 |
} |
| 71 |
} |
| 72 |
|