Skip to content

Commit 4d67f6e

Browse files
Updated safe_strlen & safe_substr to trigger PHP notice if mb_string extensions are missing and encoding is present
1 parent 5a28151 commit 4d67f6e

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

lib/cli/cli.php

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,8 @@ function menu( $items, $default = null, $title = 'Choose an item' ) {
153153
}
154154

155155
/**
156-
* An encoding-safe way of getting string length.
156+
* Attempts an encoding-safe way of getting string length. If mb_string extensions aren't
157+
* installed, falls back to basic strlen if no encoding is present
157158
*
158159
* @param string The string to check
159160
* @return int Numeric value that represents the string's length
@@ -162,25 +163,32 @@ function safe_strlen( $str ) {
162163
if ( function_exists( 'mb_strlen' ) ) {
163164
$length = mb_strlen( $str, mb_detect_encoding( $str ) );
164165
} else {
166+
// iconv will return PHP notice if non-ascii characters are present in input string
167+
$str = iconv( 'ASCII' , 'ASCII', $str );
168+
165169
$length = strlen( $str );
166170
}
167171

168172
return $length;
169173
}
170174

171175
/**
172-
* An encoding-safe way of getting a substring.
176+
* Attempts an encoding-safe way of getting a substring. If mb_string extensions aren't
177+
* installed, falls back to ascii substring if no encoding is present
173178
*
174-
* @param string $string The input string
179+
* @param string $str The input string
175180
* @param int $start The starting position of the substring
176181
* @param boolean $length Maximum length of the substring
177182
* @return string Substring of string specified by start and length parameters
178183
*/
179-
function safe_substr( $string, $start, $length = false ) {
184+
function safe_substr( $str, $start, $length = false ) {
180185
if ( function_exists( 'mb_substr' ) ) {
181-
$substr = mb_substr( $string, $start, $length, mb_detect_encoding( $string ) );
186+
$substr = mb_substr( $str, $start, $length, mb_detect_encoding( $str ) );
182187
} else {
183-
$substr = substr( $string, $start, $length );
188+
// iconv will return PHP notice if non-ascii characters are present in input string
189+
$str = iconv( 'ASCII' , 'ASCII', $str );
190+
191+
$substr = substr( $str, $start, $length );
184192
}
185193

186194
return $substr;

0 commit comments

Comments
 (0)