Created
January 10, 2016 00:38
-
-
Save jrdmb/af85cdcaabdb36f96173 to your computer and use it in GitHub Desktop.
PHP: Extract Urls from String
This file contains 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 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