$maxLength && ! empty( $maxLength ) && ! empty( $text ) ){ return function_exists( 'mb_strimwidth' ) ? mb_strimwidth( $text, 0, $maxLength, '' ) . $more : substr( $text, 0, $maxLength ) . $more; } return $text; } /** * Trims text to a certain number of words. * * @param string $text The text to be trimmed * @param int $maxLength Number of words. * @param string $more What to append if $text needs to be trimmed. Default ' …'. * * @return mixed|string */ public static function trimByWords( $text, $maxLength, $more = " ..." ) { $words = preg_split('/\s+/u', $text, $maxLength + 1); if( count( $words ) > $maxLength ) { array_pop($words); $text = implode(' ', $words); $text .= $more; } return $text; } /** * Removes a string from the end of a text * * @param string $text the original text * @param string $stringToTrim the string that should be removed from end of original text * * @return string */ public static function rightTrim( $text, $stringToTrim ) { $lengthToTrim = strlen( $stringToTrim ); $originalText = $text; $text = trim( $text ); if( substr( $text, -$lengthToTrim ) == $stringToTrim ) { return substr( $text, 0, -$lengthToTrim ); } return $originalText; } /** * Removes a string from the start of a text * * @param string $text the original text * @param string $stringToTrim the string that should be removed from start of original text * * @return string */ public static function leftTrim( $text, $stringToTrim ) { if ( strpos( $text, $stringToTrim ) === 0) { return substr( $text, strlen( $stringToTrim ) ); } return $text; } /** * Check if string ends with another string * * @param $haystack * @param $needle * * @return bool */ public static function ends( $haystack, $needle ){ $len = strlen( $needle ); if ( $len == 0 ) { return true; } return substr( $haystack, -$len ) === $needle; } /** * Check if string starts with another string * * @param $haystack * @param $needle * * @return bool */ public static function starts( $haystack, $needle ){ return 0 === strpos( $haystack, $needle ); } /** * Converts comma-separated string, empty, or null values to array * * @param mixed $value Variable to be converted * @param string $separator Separator in text-separated string * @return array */ public static function toArray( $value, $separator = ',' ){ if ( is_null( $value ) || $value === '') { return []; } elseif ( is_array( $value ) ) { return $value; } elseif ( is_string( $value ) ) { $value = array_map('trim', explode( $separator, $value ) ); // remove empty items as well return array_filter( $value, function( $item ) { return !empty( $item ); }); } else { return []; } } }