diff --git a/src/wp-admin/includes/misc.php b/src/wp-admin/includes/misc.php index d776681ccc..de6fc4e94c 100644 --- a/src/wp-admin/includes/misc.php +++ b/src/wp-admin/includes/misc.php @@ -288,21 +288,6 @@ function update_home_siteurl( $old_value, $value ) { } } -/** - * Shorten an URL, to be used as link text - * - * @since 1.2.0 - * - * @param string $url - * @return string - */ -function url_shorten( $url ) { - $short_url = str_replace( array( 'http://', 'www.' ), '', $url ); - $short_url = untrailingslashit( $short_url ); - if ( strlen( $short_url ) > 35 ) - $short_url = substr( $short_url, 0, 32 ) . '…'; - return $short_url; -} /** * Resets global variables based on $_GET and $_POST diff --git a/src/wp-includes/formatting.php b/src/wp-includes/formatting.php index be86adf95f..eeb54dba03 100644 --- a/src/wp-includes/formatting.php +++ b/src/wp-includes/formatting.php @@ -4769,3 +4769,23 @@ function wp_staticize_emoji_for_email( $mail ) { return $mail; } + +/** + * Shorten an URL, to be used as link text + * + * @since 1.2.0 + * @since 4.4.0 Moved to wp-includes/formatting.php from wp-admin/includes/misc.php and added $length param + * + * @param string $url URL to shorten + * @param int $length Maxiumum length of url to return + * @return string +*/ +function url_shorten( $url, $length = 35 ) { + $stripped = str_replace( array( 'https://', 'http://', 'www.' ), '', $url ); + $short_url = untrailingslashit( $stripped ); + + if ( strlen( $short_url ) > $length ) { + $short_url = substr( $short_url, 0, $length - 3 ) . '…'; + } + return $short_url; +} \ No newline at end of file diff --git a/tests/phpunit/tests/formatting/URLShorten.php b/tests/phpunit/tests/formatting/URLShorten.php new file mode 100644 index 0000000000..1dd1cec596 --- /dev/null +++ b/tests/phpunit/tests/formatting/URLShorten.php @@ -0,0 +1,22 @@ + 'wordpress\.org/about/philosophy', // no longer strips slashes + 'wordpress.org/about/philosophy' => 'wordpress.org/about/philosophy', + 'http://wordpress.org/about/philosophy/' => 'wordpress.org/about/philosophy', // remove http, trailing slash + 'http://www.wordpress.org/about/philosophy/' => 'wordpress.org/about/philosophy', // remove http, www + 'http://wordpress.org/about/philosophy/#box' => 'wordpress.org/about/philosophy/#box', // don't shorten 35 characters + 'http://wordpress.org/about/philosophy/#decisions' => 'wordpress.org/about/philosophy/#…', // shorten to 32 if > 35 after cleaning + ); + foreach ( $tests as $k => $v ) { + $this->assertEquals( $v, url_shorten( $k ) ); + } + + $this->assertEquals( 'wordpress.org/about/philosophy/#…', url_shorten( 'http://wordpress.org/about/philosophy/#decisions' ), 31 ); // shorten to 31 if > 34 after cleaning + } +}