Skip to content

Instantly share code, notes, and snippets.

@jrdmb
Created January 10, 2016 00:38
Show Gist options
  • Save jrdmb/af85cdcaabdb36f96173 to your computer and use it in GitHub Desktop.
Save jrdmb/af85cdcaabdb36f96173 to your computer and use it in GitHub Desktop.
PHP: Extract Urls from String
<?php
function getUrls($string) {
//adapted from: https://stackoverflow.com/questions/11588542/get-all-urls-in-a-string-with-php
$regex = '/https?\:\/\/[^\" \n]+/i';
preg_match_all($regex, $string, $matches);
//note below that we use $matches[0], this is because we have an array of arrays
foreach ($matches[0] as $url) {
$s1 = substr($url, 0, strlen($url)-2);
$s2 = '<a href="' . $s1 . '">' . $s1 . '</a>';
echo "$s2<br />\n";
}
}
$s = "Also see:
<http://www.nature.com/news/2008/081120/full/news.2008.1246.html>
<http://www.physicsforums.com/showthread.php?t=273814>
This is a string with embedded urls. Separate out just the urls and display them.";
getUrls($s);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment