Skip to content

Instantly share code, notes, and snippets.

@cyle
Last active January 26, 2016 23:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cyle/de28409d8533bb1b62d2 to your computer and use it in GitHub Desktop.
Save cyle/de28409d8533bb1b62d2 to your computer and use it in GitHub Desktop.
dank text parsing
// parse text to link-ify links, #hashtags, and @mentions
// input plain old text, get out the formatted text and info
// used by dankest.website and the dank platform https://github.com/cylesoft/dank
function parse_text($text) {
$home_url = 'https://dankest.website/';
$link_regex = '/\b(https?:\/\/)?(\S+)\.(\S+)\b/i';
$hashtag_regex = '/\#([^\s\#]+)/i';
$mention_regex = '/\@(\S+)/i';
$t = strip_tags($text);
$links_found = preg_match_all($link_regex, $t, $link_matches);
$hashtags_found = preg_match_all($hashtag_regex, $t, $hashtag_matches);
$mentions_found = preg_match_all($mention_regex, $t, $mention_matches);
$t = preg_replace_callback($link_regex, function($matches) {
$the_link = trim($matches[0]);
if (substr($the_link, 0, 4) != 'http') {
$the_link = 'http://'.$the_link;
}
// check for youtube, vimeo, mp4/mov/webm, mp3, jpg/jpeg/png/gif
if (preg_match('/(?:youtu\.be|youtube\.com)\/(?:embed\/)?(?:watch\?v=)?([^\#\&\?\s]+)/i', $the_link, $youtube_matches)) { // if youtube
return '<div class="expanded-content"><iframe width="100%" height="100%" src="https://www.youtube.com/embed/'.$youtube_matches[1].'" frameborder="0" allowfullscreen></iframe></div>';
} else if (preg_match('/vimeo\.com\/(?:video\/)?(\d+)/i', $the_link, $vimeo_matches)) { // if vimeo
return '<div class="expanded-content"><iframe width="100%" height="100%" src="https://player.vimeo.com/video/'.$vimeo_matches[1].'" frameborder="0" allowfullscreen></iframe></div>';
} else if (preg_match('/\.(?:mp4|mov|webm)$/i', $the_link)) { // if mp4/mov/webm
return '<div class="expanded-content"><video controls="controls" src="'.$the_link.'"></video></div>';
} else if (preg_match('/\.mp3$/i', $the_link)) { // if mp3
return '<div class="expanded-content"><audio controls="controls" src="'.$the_link.'"></audio></div>';
} else if (preg_match('/\.(?:jpg|jpeg|gif|png)$/i', $the_link)) { // if jpg/jpeg/png/gif
return '<div class="expanded-content"><img src="'.$the_link.'" /></div>';
} else { // just a link
return '<a href="'.$the_link.'">'.$matches[0].'</a>';
}
}, $t);
$t = preg_replace($hashtag_regex, '<a href="'.$home_url.'tagged/$1/">$0</a>', $t);
$t = preg_replace($mention_regex, '<a href="'.$home_url.'by/$1/">$0</a>', $t);
if (preg_match('/"expanded-content"/i', $t)) {
$t .= '<div class="clear"></div>'; // .clear should be css = clear: both;
}
$t = Markdown::defaultTransform($t);
return array('text' => $t, 'links' => $link_matches[0], 'mentions' => $mention_matches[1], 'hashtags' => $hashtag_matches[1]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment