|
| 1 | +<?php |
| 2 | +namespace Onvardgmbh\HelperClasses; |
| 3 | + |
| 4 | +class Text { |
| 5 | + |
| 6 | + /** |
| 7 | + * Unicode safe version of substr_replace |
| 8 | + * |
| 9 | + * @since 0.0.1 |
| 10 | + * |
| 11 | + * @link http://php.net/manual/de/function.substr-replace.php Taken from comment in PHP docs |
| 12 | + * |
| 13 | + * @param String $string |
| 14 | + * |
| 15 | + * @return String |
| 16 | + */ |
| 17 | + public static function mb_substr_replace( $string, $replacement, $start, $length = null, $encoding = null ) { |
| 18 | + |
| 19 | + if ( extension_loaded( 'mbstring' ) === true ) { |
| 20 | + $string_length = ( is_null( $encoding ) === true ) ? mb_strlen( $string ) : mb_strlen( $string, $encoding ); |
| 21 | + |
| 22 | + if ( $start < 0 ) { |
| 23 | + $start = max( 0, $string_length + $start ); |
| 24 | + } else if ( $start > $string_length ) { |
| 25 | + $start = $string_length; |
| 26 | + } |
| 27 | + |
| 28 | + if ( $length < 0 ) { |
| 29 | + $length = max( 0, $string_length - $start + $length ); |
| 30 | + } else if ( ( is_null( $length ) === true ) || ( $length > $string_length ) ) { |
| 31 | + $length = $string_length; |
| 32 | + } |
| 33 | + |
| 34 | + if ( ( $start + $length ) > $string_length ) { |
| 35 | + $length = $string_length - $start; |
| 36 | + } |
| 37 | + |
| 38 | + if ( is_null( $encoding ) === true ) { |
| 39 | + return mb_substr( $string, 0, $start ) . $replacement . mb_substr( $string, $start + $length, |
| 40 | + $string_length - $start - $length ); |
| 41 | + } |
| 42 | + |
| 43 | + return mb_substr( $string, 0, $start, $encoding ) . $replacement . mb_substr( $string, $start + $length, |
| 44 | + $string_length - $start - $length, $encoding ); |
| 45 | + } |
| 46 | + |
| 47 | + return ( is_null( $length ) === true ) ? substr_replace( $string, $replacement, |
| 48 | + $start ) : substr_replace( $string, $replacement, $start, $length ); |
| 49 | + } |
| 50 | +} |
0 commit comments