human-readable format. * * @return string */ public static function human_number( $number, $precision = 1 ) { if ( ! is_numeric( $number ) ) { return 0; } $negative = ''; if ( abs( $number ) != $number ) { //phpcs:ignore -- Loose comparison is needed here due to the negative value. $negative = '-'; $number = abs( $number ); } if ( $number < 1000 ) { return $negative ? -1 * $number : $number; } $unit = intval( log( $number, 1000 ) ); $units = [ '', 'K', 'M', 'B', 'T', 'Q' ]; if ( array_key_exists( $unit, $units ) ) { return sprintf( '%s%s%s', $negative, rtrim( number_format( $number / pow( 1000, $unit ), $precision ), '.0' ), $units[ $unit ] ); } return $number; } /** * Truncate text for given length. * * @param {string} $str Text to truncate. * @param {number} $length Length to truncate for. * @param {string} $append Append to the end if string is truncated. * * @return {string} Truncated text. */ public static function truncate( $str, $length = 110, $append = '' ) { $str = wp_strip_all_tags( $str, true ); $strlen = mb_strlen( $str ); $excerpt = mb_substr( $str, 0, $length ); // Remove part of an entity at the end. $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt ); if ( $str !== $excerpt ) { $strrpos = function_exists( 'mb_strrpos' ) ? 'mb_strrpos' : 'strrpos'; $excerpt = mb_substr( $str, 0, $strrpos( trim( $excerpt ), ' ' ) ); } if ( $strlen > $length ) { $excerpt .= $append; } return $excerpt; } /** * Multibyte ucwords. * * @param string $value String to convert. */ public static function mb_ucwords( $value ) { if ( ! function_exists( 'mb_convert_case' ) || ! function_exists( 'mb_detect_encoding' ) || mb_detect_encoding( $value ) !== 'UTF-8' ) { return ucwords( $value ); } $words = preg_split( '/([\s]+)/u', $value, -1, PREG_SPLIT_DELIM_CAPTURE ); $ucwords = ''; foreach ( $words as $word ) { if ( is_numeric( $word ) ) { $ucwords .= $word; continue; } if ( isset( $word[0] ) ) { $ucwords .= preg_match( '/[\p{L}]/u', $word[0] ) ? mb_strtoupper( $word[0], 'UTF-8' ) . mb_substr( $word, 1, mb_strlen( $word ), 'UTF-8' ) : $word; } } return $ucwords; } }