diff --git a/system/Helpers/text_helper.php b/system/Helpers/text_helper.php index 4133fe708d..d50950d173 100755 --- a/system/Helpers/text_helper.php +++ b/system/Helpers/text_helper.php @@ -1,4 +1,5 @@ = $n) - { - $out = trim($out); - - return (mb_strlen($out) === mb_strlen($str)) ? $out : $out . $end_char; - } - } - } + foreach (explode(' ', trim($str)) as $val) + { + $out .= $val . ' '; + if (mb_strlen($out) >= $n) + { + $out = trim($out); + break; + } + } + return (mb_strlen($out) === mb_strlen($str)) ? $out : $out . $end_char; + } } @@ -132,63 +133,63 @@ if ( ! function_exists('character_limiter')) if ( ! function_exists('ascii_to_entities')) { - /** - * High ASCII to Entities - * - * Converts high ASCII text and MS Word special characters to character entities - * - * @param string $str - * - * @return string - */ - function ascii_to_entities(string $str): string - { - $out = ''; + /** + * High ASCII to Entities + * + * Converts high ASCII text and MS Word special characters to character entities + * + * @param string $str + * + * @return string + */ + function ascii_to_entities(string $str): string + { + $out = ''; - for ($i = 0, $s = strlen($str) - 1, $count = 1, $temp = []; $i <= $s; $i ++ ) - { - $ordinal = ord($str[$i]); + for ($i = 0, $s = strlen($str) - 1, $count = 1, $temp = []; $i <= $s; $i ++) + { + $ordinal = ord($str[$i]); - if ($ordinal < 128) - { - /* - If the $temp array has a value but we have moved on, then it seems only - fair that we output that entity and restart $temp before continuing. -Paul - */ - if (count($temp) === 1) - { - $out .= '&#' . array_shift($temp) . ';'; - $count = 1; - } + if ($ordinal < 128) + { + /* + If the $temp array has a value but we have moved on, then it seems only + fair that we output that entity and restart $temp before continuing. -Paul + */ + if (count($temp) === 1) + { + $out .= '&#' . array_shift($temp) . ';'; + $count = 1; + } - $out .= $str[$i]; - } - else - { - if (empty($temp)) - { - $count = ($ordinal < 224) ? 2 : 3; - } + $out .= $str[$i]; + } + else + { + if (empty($temp)) + { + $count = ($ordinal < 224) ? 2 : 3; + } - $temp[] = $ordinal; + $temp[] = $ordinal; - if (count($temp) === $count) - { - $number = ($count === 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64); - $out .= '&#' . $number . ';'; - $count = 1; - $temp = []; - } - // If this is the last iteration, just output whatever we have - elseif ($i === $s) - { - $out .= '&#' . implode(';', $temp) . ';'; - } - } - } + if (count($temp) === $count) + { + $number = ($count === 3) ? (($temp[0] % 16) * 4096) + (($temp[1] % 64) * 64) + ($temp[2] % 64) : (($temp[0] % 32) * 64) + ($temp[1] % 64); + $out .= '&#' . $number . ';'; + $count = 1; + $temp = []; + } + // If this is the last iteration, just output whatever we have + elseif ($i === $s) + { + $out .= '&#' . implode(';', $temp) . ';'; + } + } + } - return $out; - } + return $out; + } } @@ -197,51 +198,51 @@ if ( ! function_exists('ascii_to_entities')) if ( ! function_exists('entities_to_ascii')) { - /** - * Entities to ASCII - * - * Converts character entities back to ASCII - * - * @param string $str - * @param bool $all - * - * @return string - */ - function entities_to_ascii(string $str, bool $all = true): string - { - if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) - { - for ($i = 0, $s = count($matches[0]); $i < $s; $i ++ ) - { - $digits = $matches[1][$i]; - $out = ''; - if ($digits < 128) - { - $out .= chr($digits); - } - elseif ($digits < 2048) - { - $out .= chr(192 + (($digits - ($digits % 64)) / 64)) . chr(128 + ($digits % 64)); - } - else - { - $out .= chr(224 + (($digits - ($digits % 4096)) / 4096)) - . chr(128 + ((($digits % 4096) - ($digits % 64)) / 64)) - . chr(128 + ($digits % 64)); - } - $str = str_replace($matches[0][$i], $out, $str); - } - } + /** + * Entities to ASCII + * + * Converts character entities back to ASCII + * + * @param string $str + * @param bool $all + * + * @return string + */ + function entities_to_ascii(string $str, bool $all = true): string + { + if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) + { + for ($i = 0, $s = count($matches[0]); $i < $s; $i ++) + { + $digits = $matches[1][$i]; + $out = ''; + if ($digits < 128) + { + $out .= chr($digits); + } + elseif ($digits < 2048) + { + $out .= chr(192 + (($digits - ($digits % 64)) / 64)) . chr(128 + ($digits % 64)); + } + else + { + $out .= chr(224 + (($digits - ($digits % 4096)) / 4096)) + . chr(128 + ((($digits % 4096) - ($digits % 64)) / 64)) + . chr(128 + ($digits % 64)); + } + $str = str_replace($matches[0][$i], $out, $str); + } + } - if ($all) - { - return str_replace( - ['&', '<', '>', '"', ''', '-'], ['&', '<', '>', '"', "'", '-'], $str - ); - } + if ($all) + { + return str_replace( + ['&', '<', '>', '"', ''', '-'], ['&', '<', '>', '"', "'", '-'], $str + ); + } - return $str; - } + return $str; + } } @@ -250,60 +251,60 @@ if ( ! function_exists('entities_to_ascii')) if ( ! function_exists('word_censor')) { - /** - * Word Censoring Function - * - * Supply a string and an array of disallowed words and any - * matched words will be converted to #### or to the replacement - * word you've submitted. - * - * @param string $str the text string - * @param string $censored the array of censored words - * @param string $replacement the optional replacement value - * - * @return string - */ - function word_censor(string $str, $censored, string $replacement = ''): string - { - if ( ! is_array($censored)) - { - return $str; - } + /** + * Word Censoring Function + * + * Supply a string and an array of disallowed words and any + * matched words will be converted to #### or to the replacement + * word you've submitted. + * + * @param string $str the text string + * @param string $censored the array of censored words + * @param string $replacement the optional replacement value + * + * @return string + */ + function word_censor(string $str, $censored, string $replacement = ''): string + { + if ( ! is_array($censored)) + { + return $str; + } - $str = ' ' . $str . ' '; + $str = ' ' . $str . ' '; - // \w, \b and a few others do not match on a unicode character - // set for performance reasons. As a result words like über - // will not match on a word boundary. Instead, we'll assume that - // a bad word will be bookeneded by any of these characters. - $delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]'; + // \w, \b and a few others do not match on a unicode character + // set for performance reasons. As a result words like über + // will not match on a word boundary. Instead, we'll assume that + // a bad word will be bookeneded by any of these characters. + $delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]'; - foreach ($censored as $badword) - { - $badword = str_replace('\*', '\w*?', preg_quote($badword, '/')); + foreach ($censored as $badword) + { + $badword = str_replace('\*', '\w*?', preg_quote($badword, '/')); - if ($replacement !== '') - { - $str = preg_replace( - "/({$delim})(" . $badword . ")({$delim})/i", "\\1{$replacement}\\3", $str - ); - } - elseif (preg_match_all("/{$delim}(" . $badword . "){$delim}/i", $str, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE)) - { - $matches = $matches[1]; + if ($replacement !== '') + { + $str = preg_replace( + "/({$delim})(" . $badword . ")({$delim})/i", "\\1{$replacement}\\3", $str + ); + } + elseif (preg_match_all("/{$delim}(" . $badword . "){$delim}/i", $str, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE)) + { + $matches = $matches[1]; - for ($i = count($matches) - 1; $i >= 0; $i -- ) - { - $length = strlen($matches[$i][0]); - $str = substr_replace( - $str, str_repeat('#', $length), $matches[$i][1], $length - ); - } - } - } + for ($i = count($matches) - 1; $i >= 0; $i --) + { + $length = strlen($matches[$i][0]); + $str = substr_replace( + $str, str_repeat('#', $length), $matches[$i][1], $length + ); + } + } + } - return trim($str); - } + return trim($str); + } } @@ -312,50 +313,50 @@ if ( ! function_exists('word_censor')) if ( ! function_exists('highlight_code')) { - /** - * Code Highlighter - * - * Colorizes code strings - * - * @param string $str the text string - * - * @return string - */ - function highlight_code(string $str): string - { - /* The highlight string function encodes and highlights - * brackets so we need them to start raw. - * - * Also replace any existing PHP tags to temporary markers - * so they don't accidentally break the string out of PHP, - * and thus, thwart the highlighting. - */ - $str = str_replace( - ['<', '>', '', '<%', '%>', '\\', ''], ['<', '>', 'phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'], $str - ); + /** + * Code Highlighter + * + * Colorizes code strings + * + * @param string $str the text string + * + * @return string + */ + function highlight_code(string $str): string + { + /* The highlight string function encodes and highlights + * brackets so we need them to start raw. + * + * Also replace any existing PHP tags to temporary markers + * so they don't accidentally break the string out of PHP, + * and thus, thwart the highlighting. + */ + $str = str_replace( + ['<', '>', '', '<%', '%>', '\\', ''], ['<', '>', 'phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'], $str + ); - // The highlight_string function requires that the text be surrounded - // by PHP tags, which we will remove later - $str = highlight_string('', true); + // The highlight_string function requires that the text be surrounded + // by PHP tags, which we will remove later + $str = highlight_string('', true); - // Remove our artificially added PHP, and the syntax highlighting that came with it - $str = preg_replace( - [ - '/<\?php( | )/i', - '/(.*?)\?><\/span>\n<\/span>\n<\/code>/is', - '/<\/span>/i', - ], [ - '', - "$1\n\n", - '', - ], $str - ); + // Remove our artificially added PHP, and the syntax highlighting that came with it + $str = preg_replace( + [ + '/<\?php( | )/i', + '/(.*?)\?><\/span>\n<\/span>\n<\/code>/is', + '/<\/span>/i', + ], [ + '', + "$1\n\n", + '', + ], $str + ); - // Replace our markers back to PHP tags. - return str_replace( - ['phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'], ['<?', '?>', '<%', '%>', '\\', '</script>'], $str - ); - } + // Replace our markers back to PHP tags. + return str_replace( + ['phptagopen', 'phptagclose', 'asptagopen', 'asptagclose', 'backslashtmp', 'scriptclose'], ['<?', '?>', '<%', '%>', '\\', '</script>'], $str + ); + } } @@ -364,22 +365,22 @@ if ( ! function_exists('highlight_code')) if ( ! function_exists('highlight_phrase')) { - /** - * Phrase Highlighter - * - * Highlights a phrase within a text string - * - * @param string $str the text string - * @param string $phrase the phrase you'd like to highlight - * @param string $tag_open the openging tag to precede the phrase with - * @param string $tag_close the closing tag to end the phrase with - * - * @return string - */ - function highlight_phrase(string $str, string $phrase, string $tag_open = '', string $tag_close = ''): string - { - return ($str !== '' && $phrase !== '') ? preg_replace('/(' . preg_quote($phrase, '/') . ')/i', $tag_open . '\\1' . $tag_close, $str) : $str; - } + /** + * Phrase Highlighter + * + * Highlights a phrase within a text string + * + * @param string $str the text string + * @param string $phrase the phrase you'd like to highlight + * @param string $tag_open the openging tag to precede the phrase with + * @param string $tag_close the closing tag to end the phrase with + * + * @return string + */ + function highlight_phrase(string $str, string $phrase, string $tag_open = '', string $tag_close = ''): string + { + return ($str !== '' && $phrase !== '') ? preg_replace('/(' . preg_quote($phrase, '/') . ')/i', $tag_open . '\\1' . $tag_close, $str) : $str; + } } @@ -388,36 +389,36 @@ if ( ! function_exists('highlight_phrase')) if ( ! function_exists('convert_accented_characters')) { - /** - * Convert Accented Foreign Characters to ASCII - * - * @param string $str Input string - * - * @return string - */ - function convert_accented_characters(string $str): string - { - static $array_from, $array_to; + /** + * Convert Accented Foreign Characters to ASCII + * + * @param string $str Input string + * + * @return string + */ + function convert_accented_characters(string $str): string + { + static $array_from, $array_to; - if ( ! is_array($array_from)) - { - $config = new Config\ForeignCharacters(); + if ( ! is_array($array_from)) + { + $config = new Config\ForeignCharacters(); - if (empty($config->characterList) || ! is_array($config->characterList)) - { - $array_from = []; - $array_to = []; + if (empty($config->characterList) || ! is_array($config->characterList)) + { + $array_from = []; + $array_to = []; - return $str; - } - $array_from = array_keys($config->characterList); - $array_to = array_values($config->characterList); + return $str; + } + $array_from = array_keys($config->characterList); + $array_to = array_values($config->characterList); - unset($config); - } + unset($config); + } - return preg_replace($array_from, $array_to, $str); - } + return preg_replace($array_from, $array_to, $str); + } } @@ -426,100 +427,103 @@ if ( ! function_exists('convert_accented_characters')) if ( ! function_exists('word_wrap')) { - /** - * Word Wrap - * - * Wraps text at the specified character. Maintains the integrity of words. - * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor - * will URLs. - * - * @param string $str the text string - * @param int $charlim = 76 the number of characters to wrap at - * - * @return string - */ - function word_wrap(string $str, int $charlim = 76): string - { - // Set the character limit - is_numeric($charlim) || $charlim = 76; + /** + * Word Wrap + * + * Wraps text at the specified character. Maintains the integrity of words. + * Anything placed between {unwrap}{/unwrap} will not be word wrapped, nor + * will URLs. + * + * @param string $str the text string + * @param int $charlim = 76 the number of characters to wrap at + * + * @return string + */ + function word_wrap(string $str, int $charlim = 76): string + { + // Set the character limit + is_numeric($charlim) || $charlim = 76; - // Reduce multiple spaces - $str = preg_replace('| +|', ' ', $str); + // Reduce multiple spaces + $str = preg_replace('| +|', ' ', $str); - // Standardize newlines - if (strpos($str, "\r") !== false) - { - $str = str_replace(["\r\n", "\r"], "\n", $str); - } + // Standardize newlines + if (strpos($str, "\r") !== false) + { + $str = str_replace(["\r\n", "\r"], "\n", $str); + } - // If the current word is surrounded by {unwrap} tags we'll - // strip the entire chunk and replace it with a marker. - $unwrap = []; + // If the current word is surrounded by {unwrap} tags we'll + // strip the entire chunk and replace it with a marker. + $unwrap = []; - if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches)) - { - for ($i = 0, $c = count($matches[0]); $i < $c; $i ++ ) - { - $unwrap[] = $matches[1][$i]; - $str = str_replace($matches[0][$i], '{{unwrapped' . $i . '}}', $str); - } - } + if (preg_match_all('|\{unwrap\}(.+?)\{/unwrap\}|s', $str, $matches)) + { + for ($i = 0, $c = count($matches[0]); $i < $c; $i ++) + { + $unwrap[] = $matches[1][$i]; + $str = str_replace($matches[0][$i], '{{unwrapped' . $i . '}}', $str); + } + } - // Use PHP's native function to do the initial wordwrap. - // We set the cut flag to FALSE so that any individual words that are - // too long get left alone. In the next step we'll deal with them. - $str = wordwrap($str, $charlim, "\n", false); + // Use PHP's native function to do the initial wordwrap. + // We set the cut flag to FALSE so that any individual words that are + // too long get left alone. In the next step we'll deal with them. + $str = wordwrap($str, $charlim, "\n", false); - // Split the string into individual lines of text and cycle through them - $output = ''; + // Split the string into individual lines of text and cycle through them + $output = ''; - foreach (explode("\n", $str) as $line) - { - // Is the line within the allowed character count? - // If so we'll join it to the output and continue - if (mb_strlen($line) <= $charlim) - { - $output .= $line . "\n"; - continue; - } + foreach (explode("\n", $str) as $line) + { + // Is the line within the allowed character count? + // If so we'll join it to the output and continue + if (mb_strlen($line) <= $charlim) + { + $output .= $line . "\n"; + continue; + } - $temp = ''; + $temp = ''; - while (mb_strlen($line) > $charlim) - { - // If the over-length word is a URL we won't wrap it - if (preg_match('!\[url.+\]|://|www\.!', $line)) - { - break; - } - // Trim the word down - $temp .= mb_substr($line, 0, $charlim - 1); - $line = mb_substr($line, $charlim - 1); - } + while (mb_strlen($line) > $charlim) + { + // If the over-length word is a URL we won't wrap it + if (preg_match('!\[url.+\]|://|www\.!', $line)) + { + break; + } + // Trim the word down + $temp .= mb_substr($line, 0, $charlim - 1); + $line = mb_substr($line, $charlim - 1); + } - // If $temp contains data it means we had to split up an over-length - // word into smaller chunks so we'll add it back to our current line - if ($temp !== '') - { - $output .= $temp . "\n" . $line . "\n"; - } - else - { - $output .= $line . "\n"; - } - } + // If $temp contains data it means we had to split up an over-length + // word into smaller chunks so we'll add it back to our current line + if ($temp !== '') + { + $output .= $temp . "\n" . $line . "\n"; + } + else + { + $output .= $line . "\n"; + } + } - // Put our markers back - if (! empty($unwrap)) - { - foreach ($unwrap as $key => $val) - { - $output = str_replace('{{unwrapped' . $key . '}}', $val, $output); - } - } + // Put our markers back + if ( ! empty($unwrap)) + { + foreach ($unwrap as $key => $val) + { + $output = str_replace('{{unwrapped' . $key . '}}', $val, $output); + } + } - return $output; - } + // remove any trailing newline + $output = rtrim($output); + + return $output; + } } @@ -528,43 +532,43 @@ if ( ! function_exists('word_wrap')) if ( ! function_exists('ellipsize')) { - /** - * Ellipsize String - * - * This function will strip tags from a string, split it at its max_length and ellipsize - * - * @param string $str String to ellipsize - * @param int $max_length Max length of string - * @param mixed $position int (1|0) or float, .5, .2, etc for position to split - * @param string $ellipsis ellipsis ; Default '...' - * - * @return string Ellipsized string - */ - function ellipsize(string $str, int $max_length, $position = 1, string $ellipsis = '…'): string - { - // Strip tags - $str = trim(strip_tags($str)); + /** + * Ellipsize String + * + * This function will strip tags from a string, split it at its max_length and ellipsize + * + * @param string $str String to ellipsize + * @param int $max_length Max length of string + * @param mixed $position int (1|0) or float, .5, .2, etc for position to split + * @param string $ellipsis ellipsis ; Default '...' + * + * @return string Ellipsized string + */ + function ellipsize(string $str, int $max_length, $position = 1, string $ellipsis = '…'): string + { + // Strip tags + $str = trim(strip_tags($str)); - // Is the string long enough to ellipsize? - if (mb_strlen($str) <= $max_length) - { - return $str; - } + // Is the string long enough to ellipsize? + if (mb_strlen($str) <= $max_length) + { + return $str; + } - $beg = mb_substr($str, 0, floor($max_length * $position)); - $position = ($position > 1) ? 1 : $position; + $beg = mb_substr($str, 0, floor($max_length * $position)); + $position = ($position > 1) ? 1 : $position; - if ($position === 1) - { - $end = mb_substr($str, 0, -($max_length - mb_strlen($beg))); - } - else - { - $end = mb_substr($str, -($max_length - mb_strlen($beg))); - } + if ($position === 1) + { + $end = mb_substr($str, 0, -($max_length - mb_strlen($beg))); + } + else + { + $end = mb_substr($str, -($max_length - mb_strlen($beg))); + } - return $beg . $ellipsis . $end; - } + return $beg . $ellipsis . $end; + } } @@ -573,28 +577,28 @@ if ( ! function_exists('ellipsize')) if ( ! function_exists('strip_slashes')) { - /** - * Strip Slashes - * - * Removes slashes contained in a string or in an array - * - * @param mixed string or array - * - * @return mixed string or array - */ - function strip_slashes($str) - { - if ( ! is_array($str)) - { - return stripslashes($str); - } - foreach ($str as $key => $val) - { - $str[$key] = strip_slashes($val); - } + /** + * Strip Slashes + * + * Removes slashes contained in a string or in an array + * + * @param mixed string or array + * + * @return mixed string or array + */ + function strip_slashes($str) + { + if ( ! is_array($str)) + { + return stripslashes($str); + } + foreach ($str as $key => $val) + { + $str[$key] = strip_slashes($val); + } - return $str; - } + return $str; + } } @@ -603,19 +607,19 @@ if ( ! function_exists('strip_slashes')) if ( ! function_exists('strip_quotes')) { - /** - * Strip Quotes - * - * Removes single and double quotes from a string - * - * @param string - * - * @return string - */ - function strip_quotes(string $str): string - { - return str_replace(['"', "'"], '', $str); - } + /** + * Strip Quotes + * + * Removes single and double quotes from a string + * + * @param string + * + * @return string + */ + function strip_quotes(string $str): string + { + return str_replace(['"', "'"], '', $str); + } } @@ -624,19 +628,19 @@ if ( ! function_exists('strip_quotes')) if ( ! function_exists('quotes_to_entities')) { - /** - * Quotes to Entities - * - * Converts single and double quotes to entities - * - * @param string - * - * @return string - */ - function quotes_to_entities(string $str): string - { - return str_replace(["\'", "\"", "'", '"'], ["'", """, "'", """], $str); - } + /** + * Quotes to Entities + * + * Converts single and double quotes to entities + * + * @param string + * + * @return string + */ + function quotes_to_entities(string $str): string + { + return str_replace(["\'", "\"", "'", '"'], ["'", """, "'", """], $str); + } } @@ -645,26 +649,26 @@ if ( ! function_exists('quotes_to_entities')) if ( ! function_exists('reduce_double_slashes')) { - /** - * Reduce Double Slashes - * - * Converts double slashes in a string to a single slash, - * except those found in http:// - * - * http://www.some-site.com//index.php - * - * becomes: - * - * http://www.some-site.com/index.php - * - * @param string - * - * @return string - */ - function reduce_double_slashes(string $str): string - { - return preg_replace('#(^|[^:])//+#', '\\1/', $str); - } + /** + * Reduce Double Slashes + * + * Converts double slashes in a string to a single slash, + * except those found in http:// + * + * http://www.some-site.com//index.php + * + * becomes: + * + * http://www.some-site.com/index.php + * + * @param string + * + * @return string + */ + function reduce_double_slashes(string $str): string + { + return preg_replace('#(^|[^:])//+#', '\\1/', $str); + } } @@ -673,29 +677,29 @@ if ( ! function_exists('reduce_double_slashes')) if ( ! function_exists('reduce_multiples')) { - /** - * Reduce Multiples - * - * Reduces multiple instances of a particular character. Example: - * - * Fred, Bill,, Joe, Jimmy - * - * becomes: - * - * Fred, Bill, Joe, Jimmy - * - * @param string $str - * @param string $character the character you wish to reduce - * @param bool $trim TRUE/FALSE - whether to trim the character from the beginning/end - * - * @return string - */ - function reduce_multiples(string $str, string $character = ',', bool $trim = false): string - { - $str = preg_replace('#' . preg_quote($character, '#') . '{2,}#', $character, $str); + /** + * Reduce Multiples + * + * Reduces multiple instances of a particular character. Example: + * + * Fred, Bill,, Joe, Jimmy + * + * becomes: + * + * Fred, Bill, Joe, Jimmy + * + * @param string $str + * @param string $character the character you wish to reduce + * @param bool $trim TRUE/FALSE - whether to trim the character from the beginning/end + * + * @return string + */ + function reduce_multiples(string $str, string $character = ',', bool $trim = false): string + { + $str = preg_replace('#' . preg_quote($character, '#') . '{2,}#', $character, $str); - return ($trim === true) ? trim($str, $character) : $str; - } + return ($trim === true) ? trim($str, $character) : $str; + } } @@ -704,51 +708,51 @@ if ( ! function_exists('reduce_multiples')) if ( ! function_exists('random_string')) { - /** - * Create a Random String - * - * Useful for generating passwords or hashes. - * - * @param string $type Type of random string. basic, alpha, alnum, numeric, nozero, unique, md5, sha1, and crypto - * @param int $len Number of characters - * - * @return string - */ - function random_string(string $type = 'alnum', int $len = 8): string - { - switch ($type) - { - case 'basic': - return mt_rand(); - case 'alnum': - case 'numeric': - case 'nozero': - case 'alpha': - switch ($type) - { - case 'alpha': - $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - break; - case 'alnum': - $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - break; - case 'numeric': - $pool = '0123456789'; - break; - case 'nozero': - $pool = '123456789'; - break; - } + /** + * Create a Random String + * + * Useful for generating passwords or hashes. + * + * @param string $type Type of random string. basic, alpha, alnum, numeric, nozero, md5, sha1, and crypto + * @param int $len Number of characters + * + * @return string + */ + function random_string(string $type = 'alnum', int $len = 8): string + { + switch ($type) + { + case 'alnum': + case 'numeric': + case 'nozero': + case 'alpha': + switch ($type) + { + case 'alpha': + $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + break; + case 'alnum': + $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + break; + case 'numeric': + $pool = '0123456789'; + break; + case 'nozero': + $pool = '123456789'; + break; + } - return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len); - case 'md5': - return md5(uniqid(mt_rand(), true)); - case 'sha1': - return sha1(uniqid(mt_rand(), true)); - case 'crypto': - return bin2hex(random_bytes($len/2)); - } - } + return substr(str_shuffle(str_repeat($pool, ceil($len / strlen($pool)))), 0, $len); + case 'md5': + return md5(uniqid(mt_rand(), true)); + case 'sha1': + return sha1(uniqid(mt_rand(), true)); + case 'crypto': + return bin2hex(random_bytes($len / 2)); + } + // 'basic' type treated as default + return (string) mt_rand(); + } } @@ -757,21 +761,21 @@ if ( ! function_exists('random_string')) if ( ! function_exists('increment_string')) { - /** - * Add's _1 to a string or increment the ending number to allow _2, _3, etc - * - * @param string $str Required - * @param string $separator What should the duplicate number be appended with - * @param int $first Which number should be used for the first dupe increment - * - * @return string - */ - function increment_string(string $str, string $separator = '_', int $first = 1): string - { - preg_match('/(.+)' . preg_quote($separator, '/') . '([0-9]+)$/', $str, $match); + /** + * Add's _1 to a string or increment the ending number to allow _2, _3, etc + * + * @param string $str Required + * @param string $separator What should the duplicate number be appended with + * @param int $first Which number should be used for the first dupe increment + * + * @return string + */ + function increment_string(string $str, string $separator = '_', int $first = 1): string + { + preg_match('/(.+)' . preg_quote($separator, '/') . '([0-9]+)$/', $str, $match); - return isset($match[2]) ? $match[1] . $separator . ($match[2] + 1) : $str . $separator . $first; - } + return isset($match[2]) ? $match[1] . $separator . ($match[2] + 1) : $str . $separator . $first; + } } @@ -780,30 +784,30 @@ if ( ! function_exists('increment_string')) if ( ! function_exists('alternator')) { - /** - * Alternator - * - * Allows strings to be alternated. See docs... - * - * @param string (as many parameters as needed) - * - * @return string - */ - function alternator(): string - { - static $i; + /** + * Alternator + * + * Allows strings to be alternated. See docs... + * + * @param string (as many parameters as needed) + * + * @return string + */ + function alternator(): string + { + static $i; - if (func_num_args() === 0) - { - $i = 0; + if (func_num_args() === 0) + { + $i = 0; - return ''; - } + return ''; + } - $args = func_get_args(); + $args = func_get_args(); - return $args[($i ++ % count($args))]; - } + return $args[($i ++ % count($args))]; + } } @@ -812,65 +816,65 @@ if ( ! function_exists('alternator')) if ( ! function_exists('excerpt')) { - /** - * Excerpt. - * - * Allows to extract a piece of text surrounding a word or phrase. - * - * @param string $text String to search the phrase - * @param string $phrase Phrase that will be searched for. - * @param int $radius The amount of characters returned arround the phrase. - * @param string $ellipsis Ending that will be appended - * - * @return string - * - * If no $phrase is passed, will generate an excerpt of $radius characters - * from the begining of $text. - */ - function excerpt(string $text, string $phrase = null, int $radius = 100, string $ellipsis = '...'): string - { - if (isset($phrase)) - { - $phrasePos = strpos(strtolower($text), strtolower($phrase)); - $phraseLen = strlen($phrase); - } - elseif ( ! isset($phrase)) - { - $phrasePos = $radius / 2; - $phraseLen = 1; - } + /** + * Excerpt. + * + * Allows to extract a piece of text surrounding a word or phrase. + * + * @param string $text String to search the phrase + * @param string $phrase Phrase that will be searched for. + * @param int $radius The amount of characters returned arround the phrase. + * @param string $ellipsis Ending that will be appended + * + * @return string + * + * If no $phrase is passed, will generate an excerpt of $radius characters + * from the begining of $text. + */ + function excerpt(string $text, string $phrase = null, int $radius = 100, string $ellipsis = '...'): string + { + if (isset($phrase)) + { + $phrasePos = strpos(strtolower($text), strtolower($phrase)); + $phraseLen = strlen($phrase); + } + elseif ( ! isset($phrase)) + { + $phrasePos = $radius / 2; + $phraseLen = 1; + } - $pre = explode(' ', substr($text, 0, $phrasePos)); - $pos = explode(' ', substr($text, $phrasePos + $phraseLen)); + $pre = explode(' ', substr($text, 0, $phrasePos)); + $pos = explode(' ', substr($text, $phrasePos + $phraseLen)); - $prev = ' '; - $post = ' '; - $count = 0; + $prev = ' '; + $post = ' '; + $count = 0; - foreach (array_reverse($pre) as $pr => $e) - { - if ((strlen($e) + $count + 1) < $radius) - { - $prev = ' ' . $e . $prev; - } - $count = ++ $count + strlen($e); - } + foreach (array_reverse($pre) as $pr => $e) + { + if ((strlen($e) + $count + 1) < $radius) + { + $prev = ' ' . $e . $prev; + } + $count = ++ $count + strlen($e); + } - $count = 0; + $count = 0; - foreach ($pos as $po => $s) - { - if ((strlen($s) + $count + 1) < $radius) - { - $post .= $s . ' '; - } - $count = ++ $count + strlen($s); - } + foreach ($pos as $po => $s) + { + if ((strlen($s) + $count + 1) < $radius) + { + $post .= $s . ' '; + } + $count = ++ $count + strlen($s); + } - $ellPre = $phrase ? $ellipsis : ''; + $ellPre = $phrase ? $ellipsis : ''; - return str_replace(' ', ' ', $ellPre . $prev . $phrase . $post . $ellipsis); - } + return str_replace(' ', ' ', $ellPre . $prev . $phrase . $post . $ellipsis); + } - //-------------------------------------------------------------------- + //-------------------------------------------------------------------- } diff --git a/tests/system/Helpers/TextHelperTest.php b/tests/system/Helpers/TextHelperTest.php index 7abf703238..e1f0d3c043 100755 --- a/tests/system/Helpers/TextHelperTest.php +++ b/tests/system/Helpers/TextHelperTest.php @@ -1,12 +1,15 @@ -assertEquals($expected, strip_slashes($str)); - } + { + $expected = [ + "Is your name O'reilly?", + "No, my name is O'connor." + ]; + $str = [ + "Is your name O\'reilly?", + "No, my name is O\'connor." + ]; + $this->assertEquals($expected, strip_slashes($str)); + } - // -------------------------------------------------------------------- - public function test_strip_quotes() - { - $strs = [ - '"me oh my!"' => 'me oh my!', - "it's a winner!" => 'its a winner!', - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, strip_quotes($str)); - } - } + // -------------------------------------------------------------------- + public function test_strip_quotes() + { + $strs = [ + '"me oh my!"' => 'me oh my!', + "it's a winner!" => 'its a winner!', + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, strip_quotes($str)); + } + } - // -------------------------------------------------------------------- - public function test_quotes_to_entities() - { - $strs = [ - '"me oh my!"' => '"me oh my!"', - "it's a winner!" => 'it's a winner!', - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, quotes_to_entities($str)); - } - } + // -------------------------------------------------------------------- + public function test_quotes_to_entities() + { + $strs = [ + '"me oh my!"' => '"me oh my!"', + "it's a winner!" => 'it's a winner!', + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, quotes_to_entities($str)); + } + } - // -------------------------------------------------------------------- - public function test_reduce_double_slashes() - { - $strs = [ - 'http://codeigniter.com' => 'http://codeigniter.com', - '//var/www/html/example.com/' => '/var/www/html/example.com/', - '/var/www/html//index.php' => '/var/www/html/index.php' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, reduce_double_slashes($str)); - } - } + // -------------------------------------------------------------------- + public function test_reduce_double_slashes() + { + $strs = [ + 'http://codeigniter.com' => 'http://codeigniter.com', + '//var/www/html/example.com/' => '/var/www/html/example.com/', + '/var/www/html//index.php' => '/var/www/html/index.php' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, reduce_double_slashes($str)); + } + } - // -------------------------------------------------------------------- - public function test_reduce_multiples() - { - $strs = [ - 'Fred, Bill,, Joe, Jimmy' => 'Fred, Bill, Joe, Jimmy', - 'Ringo, John, Paul,,' => 'Ringo, John, Paul,' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, reduce_multiples($str)); - } - $strs = [ - 'Fred, Bill,, Joe, Jimmy' => 'Fred, Bill, Joe, Jimmy', - 'Ringo, John, Paul,,' => 'Ringo, John, Paul' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, reduce_multiples($str, ',', TRUE)); - } - } + // -------------------------------------------------------------------- + public function test_reduce_multiples() + { + $strs = [ + 'Fred, Bill,, Joe, Jimmy' => 'Fred, Bill, Joe, Jimmy', + 'Ringo, John, Paul,,' => 'Ringo, John, Paul,' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, reduce_multiples($str)); + } + $strs = [ + 'Fred, Bill,, Joe, Jimmy' => 'Fred, Bill, Joe, Jimmy', + 'Ringo, John, Paul,,' => 'Ringo, John, Paul' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, reduce_multiples($str, ',', TRUE)); + } + } - // -------------------------------------------------------------------- - public function test_random_string() - { - $this->assertEquals(16, strlen(random_string('alnum', 16))); - $this->assertInternalType('string', random_string('numeric', 16)); - $this->assertEquals(16, strlen($random = random_string('crypto', 16))); - $this->assertInternalType('string', $random); - } + // -------------------------------------------------------------------- + public function test_random_string() + { + $this->assertEquals(16, strlen(random_string('alnum', 16))); + $this->assertEquals(16, strlen(random_string('alpha', 16))); + $this->assertEquals(16, strlen(random_string('nozero', 16))); + $this->assertEquals(16, strlen(random_string('numeric', 16))); + $this->assertEquals(8, strlen(random_string('numeric'))); - // -------------------------------------------------------------------- - public function test_increment_string() - { - $this->assertEquals('my-test_1', increment_string('my-test')); - $this->assertEquals('my-test-1', increment_string('my-test', '-')); - $this->assertEquals('file_5', increment_string('file_4')); - $this->assertEquals('file-5', increment_string('file-4', '-')); - $this->assertEquals('file-5', increment_string('file-4', '-')); - $this->assertEquals('file-1', increment_string('file', '-', '1')); - $this->assertEquals(124, increment_string('123', '')); - } + $this->assertInternalType('string', random_string('basic')); + $this->assertEquals(16, strlen($random = random_string('crypto', 16))); + $this->assertInternalType('string', $random); - // ------------------------------------------------------------------- - // Functions from text_helper_test.php - // ------------------------------------------------------------------- + $this->assertEquals(32, strlen($random = random_string('md5'))); + $this->assertEquals(40, strlen($random = random_string('sha1'))); + } - public function test_word_limiter() - { - $this->assertEquals('Once upon a time,…', word_limiter($this->_long_string, 4)); - $this->assertEquals('Once upon a time,…', word_limiter($this->_long_string, 4, '…')); - $this->assertEquals('', word_limiter('', 4)); - } + // -------------------------------------------------------------------- + public function test_increment_string() + { + $this->assertEquals('my-test_1', increment_string('my-test')); + $this->assertEquals('my-test-1', increment_string('my-test', '-')); + $this->assertEquals('file_5', increment_string('file_4')); + $this->assertEquals('file-5', increment_string('file-4', '-')); + $this->assertEquals('file-5', increment_string('file-4', '-')); + $this->assertEquals('file-1', increment_string('file', '-', '1')); + $this->assertEquals(124, increment_string('123', '')); + } - // ------------------------------------------------------------------------ - public function test_character_limiter() - { - $this->assertEquals('Once upon a time, a…', character_limiter($this->_long_string, 20)); - $this->assertEquals('Once upon a time, a…', character_limiter($this->_long_string, 20, '…')); - $this->assertEquals('Short', character_limiter('Short', 20)); - $this->assertEquals('Short', character_limiter('Short', 5)); - } + // ------------------------------------------------------------------- + // Functions from text_helper_test.php + // ------------------------------------------------------------------- - // ------------------------------------------------------------------------ - public function test_ascii_to_entities() - { - $strs = [ - '“‘ “test”' => '“‘ “test”', - '†¥¨ˆøåß∂ƒ©˙∆˚¬' => '†¥¨ˆøåß∂ƒ©˙∆˚¬' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, ascii_to_entities($str)); - } - } + public function test_word_limiter() + { + $this->assertEquals('Once upon a time,…', word_limiter($this->_long_string, 4)); + $this->assertEquals('Once upon a time,…', word_limiter($this->_long_string, 4, '…')); + $this->assertEquals('', word_limiter('', 4)); + $this->assertEquals('Once upon a…', word_limiter($this->_long_string, 3, '…')); + $this->assertEquals('Once upon a time', word_limiter('Once upon a time', 4, '…')); + } - // ------------------------------------------------------------------------ - public function test_entities_to_ascii() - { - $strs = [ - '“‘ “test”' => '“‘ “test”', - '†¥¨ˆøåß∂ƒ©˙∆˚¬' => '†¥¨ˆøåß∂ƒ©˙∆˚¬' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, entities_to_ascii($str)); - } - } + // ------------------------------------------------------------------------ + public function test_character_limiter() + { + $this->assertEquals('Once upon a time, a…', character_limiter($this->_long_string, 20)); + $this->assertEquals('Once upon a time, a…', character_limiter($this->_long_string, 20, '…')); + $this->assertEquals('Short', character_limiter('Short', 20)); + $this->assertEquals('Short', character_limiter('Short', 5)); + } - // ------------------------------------------------------------------------ - public function test_convert_accented_characters() - { - //$this->ci_vfs_clone('application/Config/ForeignChars.php'); - $this->assertEquals('AAAeEEEIIOOEUUUeY', convert_accented_characters('ÀÂÄÈÊËÎÏÔŒÙÛÜŸ')); - $this->assertEquals('a e i o u n ue', convert_accented_characters('á é í ó ú ñ ü')); - } + // ------------------------------------------------------------------------ + public function test_ascii_to_entities() + { + $strs = [ + '“‘ “test” ' => '“‘ “test” ', + '†¥¨ˆøåß∂ƒ©˙∆˚¬' => '†¥¨ˆøåß∂ƒ©˙∆˚¬' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, ascii_to_entities($str)); + } + } - // ------------------------------------------------------------------------ - public function test_censored_words() - { - $censored = ['boob', 'nerd', 'ass', 'fart']; - $strs = [ - 'Ted bobbled the ball' => 'Ted bobbled the ball', - 'Jake is a nerdo' => 'Jake is a nerdo', - 'The borg will assimilate you' => 'The borg will assimilate you', - 'Did Mary Fart?' => 'Did Mary $*#?', - 'Jake is really a boob' => 'Jake is really a $*#' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, word_censor($str, $censored, '$*#')); - } - // test censored words being sent as a string - $this->assertEquals('test', word_censor('test', 'test')); - } + // ------------------------------------------------------------------------ + public function test_entities_to_ascii() + { + $strs = [ + '“‘ “test” ' => '“‘ “test” ', + '†¥¨ˆøåß∂ƒ©˙∆˚¬' => '†¥¨ˆøåß∂ƒ©˙∆˚¬' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, entities_to_ascii($str)); + } + } - // ------------------------------------------------------------------------ - public function test_highlight_code() - { - $expect = "\n<?php var_dump(\$this); ?> \n\n"; - $this->assertEquals($expect, highlight_code('')); - } + public function testEntitiesToAsciiUnsafe() + { + $str = '<>'; + $this->assertEquals('<>', entities_to_ascii($str, true)); + $this->assertEquals('<>', entities_to_ascii($str, false)); + } - // ------------------------------------------------------------------------ - public function test_highlight_phrase() - { - $strs = [ - 'this is a phrase' => 'this is a phrase', - 'this is another' => 'this is another', - 'Gimme a test, Sally' => 'Gimme a test, Sally', - 'Or tell me what this is' => 'Or tell me what this is', - '' => '' - ]; - foreach ($strs as $str => $expect) - { - $this->assertEquals($expect, highlight_phrase($str, 'this is')); - } - $this->assertEquals('this is a strong test', highlight_phrase('this is a strong test', 'this is', '', '')); - } + public function testEntitiesToAsciiSmallOrdinals() + { + $str = ''; + $this->assertEquals(pack('c', 7), entities_to_ascii($str)); + } - // ------------------------------------------------------------------------ - public function test_ellipsize() - { - $strs = [ - '0' => [ - 'this is my string' => '… my string', - "here's another one" => '…nother one', - 'this one is just a bit longer' => '…bit longer', - 'short' => 'short' - ], - '.5' => [ - 'this is my string' => 'this …tring', - "here's another one" => "here'…r one", - 'this one is just a bit longer' => 'this …onger', - 'short' => 'short' - ], - '1' => [ - 'this is my string' => 'this is my…', - "here's another one" => "here's ano…", - 'this one is just a bit longer' => 'this one i…', - 'short' => 'short' - ], - ]; - foreach ($strs as $pos => $s) - { - foreach ($s as $str => $expect) - { - $this->assertEquals($expect, ellipsize($str, 10, $pos)); - } - } - } + // ------------------------------------------------------------------------ + public function test_convert_accented_characters() + { + //$this->ci_vfs_clone('application/Config/ForeignChars.php'); + $this->assertEquals('AAAeEEEIIOOEUUUeY', convert_accented_characters('ÀÂÄÈÊËÎÏÔŒÙÛÜŸ')); + $this->assertEquals('a e i o u n ue', convert_accented_characters('á é í ó ú ñ ü')); + } - // ------------------------------------------------------------------------ - public function test_word_wrap() - { - $string = 'Here is a simple string of text that will help us demonstrate this function.'; - $this->assertEquals(substr_count(word_wrap($string, 25), "\n"), 4); - } + // ------------------------------------------------------------------------ + public function test_censored_words() + { + $censored = ['boob', 'nerd', 'ass', 'fart']; + $strs = [ + 'Ted bobbled the ball' => 'Ted bobbled the ball', + 'Jake is a nerdo' => 'Jake is a nerdo', + 'The borg will assimilate you' => 'The borg will assimilate you', + 'Did Mary Fart?' => 'Did Mary $*#?', + 'Jake is really a boob' => 'Jake is really a $*#', + 'Jake is really a (boob)' => 'Jake is really a ($*#)' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, word_censor($str, $censored, '$*#')); + } + // test censored words being sent as a string + $this->assertEquals('this is a test', word_censor('this is a test', 'test')); + } - // ------------------------------------------------------------------------ - public function test_default_word_wrap_charlim() - { - $string = "Here is a longer string of text that will help us demonstrate the default charlim of this function."; - $this->assertEquals(strpos(word_wrap($string), "\n"), 73); - } + // ------------------------------------------------------------------------ + public function test_highlight_code() + { + $expect = "\n<?php var_dump(\$this); ?> \n\n"; + $this->assertEquals($expect, highlight_code('')); + } - // ----------------------------------------------------------------------- + // ------------------------------------------------------------------------ + public function test_highlight_phrase() + { + $strs = [ + 'this is a phrase' => 'this is a phrase', + 'this is another' => 'this is another', + 'Gimme a test, Sally' => 'Gimme a test, Sally', + 'Or tell me what this is' => 'Or tell me what this is', + '' => '' + ]; + foreach ($strs as $str => $expect) + { + $this->assertEquals($expect, highlight_phrase($str, 'this is')); + } + $this->assertEquals('this is a strong test', highlight_phrase('this is a strong test', 'this is', '', '')); + } - public function test_excerpt() - { - $string = $this->_long_string; - $result = ' Once upon a time, a framework had no tests. It sad So some nice people began to write tests. The more time that went on, the happier it became. ...'; - $this->assertEquals(excerpt($string), $result); - } + // ------------------------------------------------------------------------ + public function test_ellipsize() + { + $strs = [ + '0' => [ + 'this is my string' => '… my string', + "here's another one" => '…nother one', + 'this one is just a bit longer' => '…bit longer', + 'short' => 'short' + ], + '.5' => [ + 'this is my string' => 'this …tring', + "here's another one" => "here'…r one", + 'this one is just a bit longer' => 'this …onger', + 'short' => 'short' + ], + '1' => [ + 'this is my string' => 'this is my…', + "here's another one" => "here's ano…", + 'this one is just a bit longer' => 'this one i…', + 'short' => 'short' + ], + ]; + foreach ($strs as $pos => $s) + { + foreach ($s as $str => $expect) + { + $this->assertEquals($expect, ellipsize($str, 10, $pos)); + } + } + } - // ----------------------------------------------------------------------- + // ------------------------------------------------------------------------ + public function testWordWrap() + { + $string = 'Here is a simple string of text that will help us demonstrate this function.'; + $expected = "Here is a simple string\nof text that will help us\ndemonstrate this\nfunction."; + $this->assertEquals(substr_count(word_wrap($string, 25), "\n"), 3); + $this->assertEquals($expected, word_wrap($string, 25)); - public function test_excerpt_radius() - { - $string = $this->_long_string; - $phrase = 'began'; - $result = '... people began to ...'; - $this->assertEquals(excerpt($string, $phrase, 10), $result); - } + $string2 = "Here is a\nbroken up sentence\rspanning lines\r\nwoohoo!"; + $expected2 = "Here is a\nbroken up sentence\nspanning lines\nwoohoo!"; + $this->assertEquals(substr_count(word_wrap($string2, 25), "\n"), 3); + $this->assertEquals($expected2, word_wrap($string2, 25)); - // ----------------------------------------------------------------------- + $string3 = "Here is another slightly longer\nbroken up sentence\rspanning lines\r\nwoohoo!"; + $expected3 = "Here is another slightly\nlonger\nbroken up sentence\nspanning lines\nwoohoo!"; + $this->assertEquals(substr_count(word_wrap($string3, 25), "\n"), 4); + $this->assertEquals($expected3, word_wrap($string3, 25)); + } - public function test_alternator() - { - $phrase = ' scream! '; - $result = ''; - alternator(); - for ($i = 0; $i < 4; $i ++ ) - $result .= alternator('I', 'you', 'we') . $phrase; - $this->assertEquals('I scream! you scream! we scream! I scream! ', $result); - } + public function testWordWrapUnwrap() + { + $string = 'Here is a {unwrap}simple string of text{/unwrap} that will help us demonstrate this function.'; + $expected = "Here is a simple string of text\nthat will help us\ndemonstrate this\nfunction."; + $this->assertEquals(substr_count(word_wrap($string, 25), "\n"), 3); + $this->assertEquals($expected, word_wrap($string, 25)); + } + + public function testWordWrapLongWords() + { + // the really really long word will be split + $string = 'Here is an unbelievable super-complicated and reallyreallyquiteextraordinarily sophisticated sentence.'; + $expected = "Here is an unbelievable\nsuper-complicated and\nreallyreallyquiteextraor\ndinarily\nsophisticated sentence."; + $this->assertEquals($expected, word_wrap($string, 25)); + } + + public function testWordWrapURL() + { + // the really really long word will be split + $string = 'Here is an unbelievable super-complicated and http://www.reallyreallyquiteextraordinarily.com sophisticated sentence.'; + $expected = "Here is an unbelievable\nsuper-complicated and\nhttp://www.reallyreallyquiteextraordinarily.com\nsophisticated sentence."; + $this->assertEquals($expected, word_wrap($string, 25)); + } + + // ------------------------------------------------------------------------ + public function test_default_word_wrap_charlim() + { + $string = "Here is a longer string of text that will help us demonstrate the default charlim of this function."; + $this->assertEquals(strpos(word_wrap($string), "\n"), 73); + } + + // ----------------------------------------------------------------------- + + public function test_excerpt() + { + $string = $this->_long_string; + $result = ' Once upon a time, a framework had no tests. It sad So some nice people began to write tests. The more time that went on, the happier it became. ...'; + $this->assertEquals(excerpt($string), $result); + } + + // ----------------------------------------------------------------------- + + public function test_excerpt_radius() + { + $string = $this->_long_string; + $phrase = 'began'; + $result = '... people began to ...'; + $this->assertEquals(excerpt($string, $phrase, 10), $result); + } + + // ----------------------------------------------------------------------- + + public function test_alternator() + { + $phrase = ' scream! '; + $result = ''; + alternator(); + for ($i = 0; $i < 4; $i ++ ) + $result .= alternator('I', 'you', 'we') . $phrase; + $this->assertEquals('I scream! you scream! we scream! I scream! ', $result); + } + + public function test_empty_alternator() + { + $phrase = ' scream! '; + $result = ''; + for ($i = 0; $i < 4; $i ++ ) + $result .= alternator() . $phrase; + $this->assertEquals(' scream! scream! scream! scream! ', $result); + } - public function test_empty_alternator() - { - $phrase = ' scream! '; - $result = ''; - for ($i = 0; $i < 4; $i ++ ) - $result .= alternator() . $phrase; - $this->assertEquals(' scream! scream! scream! scream! ', $result); - } } diff --git a/user_guide_src/source/helpers/text_helper.rst b/user_guide_src/source/helpers/text_helper.rst index ea6b2b2053..aba2361db3 100755 --- a/user_guide_src/source/helpers/text_helper.rst +++ b/user_guide_src/source/helpers/text_helper.rst @@ -38,7 +38,7 @@ The following functions are available: - **alpha**: A string with lower and uppercase letters only. - **alnum**: Alpha-numeric string with lower and uppercase characters. - - **basic**: A random number based on ``mt_rand()``. + - **basic**: A random number based on ``mt_rand()`` (length ignored). - **numeric**: Numeric string. - **nozero**: Numeric string with no zeros. - **md5**: An encrypted random number based on ``md5()`` (fixed length of 32). @@ -352,6 +352,8 @@ The following functions are available: // demonstrate this // function. + Excessively long words will be split, but URLs will not be. + .. php:function:: ellipsize($str, $max_length[, $position = 1[, $ellipsis = '…']]) :param string $str: Input string