From d481d1d904ef9a2f9b2dabbd357bb46f2132b9a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 07:54:13 +0000 Subject: [PATCH] Handle mb_strlen() failure in safe_strlen() On PHP < 8, mb_strlen() returns false on failure. Fall back to strlen() in that case instead of returning false, and only subtract combining characters if preg_match_all() succeeds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HsH4o5pKmm1Qd5cqwAm7vB --- lib/cli/cli.php | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/lib/cli/cli.php b/lib/cli/cli.php index d412b96..658f2a9 100755 --- a/lib/cli/cli.php +++ b/lib/cli/cli.php @@ -185,14 +185,20 @@ function safe_strlen( $str, $encoding = false ) { $encoding = mb_detect_encoding( $str, null, true /*strict*/ ); } $length = is_string( $encoding ) ? mb_strlen( $str, $encoding ) : mb_strlen( $str ); // mbstring funcs can fail if given `$encoding` arg that evals to false. - if ( 'UTF-8' === $encoding ) { - // Subtract combining characters. - $m_regex = get_unicode_regexs( 'm' ); - assert( is_string( $m_regex ) ); - $length -= preg_match_all( $m_regex, $str, $dummy /*needed for PHP 5.3*/ ); - } - if ( ! $test_safe_strlen || ( $test_safe_strlen & 4 ) ) { - return $length; + // `mb_strlen()` returns false on failure in PHP < 8, in which case fall back to `strlen()` (which also covers the empty string). + if ( $length ) { + if ( 'UTF-8' === $encoding ) { + // Subtract combining characters. + $m_regex = get_unicode_regexs( 'm' ); + assert( is_string( $m_regex ) ); + $combining_count = preg_match_all( $m_regex, $str, $dummy /*needed for PHP 5.3*/ ); + if ( false !== $combining_count ) { + $length -= $combining_count; + } + } + if ( ! $test_safe_strlen || ( $test_safe_strlen & 4 ) ) { + return $length; + } } } return strlen( $str );