Created
November 24, 2017 13:32
-
-
Save mariovalney/61c7fcf80ee555b266994136ed35e5f3 to your computer and use it in GitHub Desktop.
A function to wrap a string with "A" HTML tag if it's a link
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function wrap_with_link( $string ) { | |
| /** | |
| * The Regex: | |
| * | |
| * From the start of the string we look for http or https protocols or just "://" | |
| * After that we look for one or more not-whitespace string plus dot in the end | |
| * After that we look for one not-whitespace-with-2-or-3 string | |
| * In the end we look for one '?' or '/' character and than zero or more not-whitespace string | |
| */ | |
| $regex = '/^(?:(?:http(?:s)?)?:\/\/)?(?:[\S]+\.{1})+(?:[\S]{2,3}){1}(?:[?\/]{1}[\S]*)*$/i'; | |
| if ( preg_match( $regex, $string ) ) { | |
| // The function 'esc_url' is from WordPress: you can remove it or create a URL parser when using it outside WP | |
| return '<a href="' . esc_url( $string ) . '" target="_blank">' . $string . '</a>'; | |
| } | |
| return $string; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment