Skip to content

Instantly share code, notes, and snippets.

@mariovalney
Created November 24, 2017 13:32
Show Gist options
  • Save mariovalney/61c7fcf80ee555b266994136ed35e5f3 to your computer and use it in GitHub Desktop.
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
<?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