Skip to content

Instantly share code, notes, and snippets.

@aaronott
Last active December 11, 2015 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronott/4551942 to your computer and use it in GitHub Desktop.
Save aaronott/4551942 to your computer and use it in GitHub Desktop.
Find any url in a string and replace it with a clickable lin
#!/usr/bin/env php
<?php
function create_link($msg) {
$pattern = array(
'/(((http|https|ftp|ftps)\:\/\/)(?:[\w\-\d]+\.)+[\w\-\d]+(?:\/[\w\-\d]+)*(?:\/|\.[\w\-\d]+)?(?:\?[\w\-\d]+\=[\w\-\d\+]+)?(?:\&[\w\-\d]+\=[\w\-\d\+\.\%]+)*(?:\#[\w\-\d]*)?)/',
);
$replace = array(
'<a href="$1">$1</a> [<a href="$1" target="_blank">^</a>]' ,
);
$msg = preg_replace( $pattern , $replace , $msg );
return stripslashes( utf8_encode( $msg ) );
}
$teststr = "
This will match and link the following url
https://www.google.com/search?num=100&hl=en&tbo=d&q=this+is+a+quick+search&oq=this+is+a+quick+search";
echo create_link($teststr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment