Last active
December 17, 2019 15:41
-
-
Save MartinTale/70941c5393110331c6ec7ace9884ab43 to your computer and use it in GitHub Desktop.
Laravel helper function that turn hashtags in a string into links..
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 | |
if (! function_exists('hashTagToLink')) | |
{ | |
function hashTagToLink($string) | |
{ | |
$hashTagMap = [ | |
'book' => 'books', | |
]; | |
$hashTags = []; | |
preg_match_all('/#(\w+)/', $string, $hashTags); | |
$processedHashTags = []; | |
foreach ($hashTags[1] as $hashTag) { | |
if (! in_array($hashTag, $processedHashTags)) { | |
if (! empty($hashTagMap[$hashTag])) { | |
$hashTagLink = $hashTagMap[$hashTag]; | |
} else { | |
$hashTagLink = $hashTag; | |
} | |
$string = str_replace('#' . $hashTag, '<a href="' . route('project', $hashTagLink) . '">#' . $hashTag . '</a>', $string); | |
$processedHashTags[] = $hashTag; | |
} | |
} | |
return $string; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment