Skip to content

Instantly share code, notes, and snippets.

@FabianSchmick
Forked from ShNURoK42/MyParsedown
Created November 20, 2018 08:43
Show Gist options
  • Save FabianSchmick/7d2232819d6e77573d66b32792e2ebaf to your computer and use it in GitHub Desktop.
Save FabianSchmick/7d2232819d6e77573d66b32792e2ebaf to your computer and use it in GitHub Desktop.
Mention for Parsedown
<?php
class MyParsedown extends \Parsedown
{
function __construct()
{
$this->InlineTypes['@'][]= 'UserMention';
$this->inlineMarkerList .= '@';
}
protected function inlineUserMention($Excerpt)
{
if (preg_match('/\B@([a-zA-Z][\w-]+)/', $Excerpt['context'], $matches)) {
// Find user by username. You have do it something else.
$user = User::findByUsername($matches[1]);
if ($user) {
return [
'extent' => strlen($matches[0]),
'element' => [
'name' => 'a',
'text' => $matches[0],
'attributes' => [
'href' => '/user/' . $user->id, //link to username profile
'class' => 'user-mention', //style class of url
],
],
];
} else {
return [
'markup' => $matches[0],
'extent' => strlen($matches[0]),
];
}
}
}
public static function findMentions($text)
{
$pattern = '/\B@([a-zA-Z][\w-]+)/';
if (preg_match_all($pattern, $text)) {
$text = str_replace(["\r\n", "\r"], "\n", $text);
$text = trim($text, "\n");
$lines = explode("\n", $text);
$mentions = [];
$isBlockCode = false;
foreach ($lines as $line) {
if (empty($line)) {
continue;
}
if (($l = $line[0]) === '`' && strncmp($line, '```', 3) === 0 || $l === '~' && strncmp($line, '~~~', 3) === 0) {
if ($isBlockCode === false) {
$isBlockCode = true;
} else {
$isBlockCode = false;
}
continue;
} elseif ($isBlockCode === true) {
continue;
} elseif (($l = $line[0]) === ' ' && $line[1] === ' ' && $line[2] === ' ' && $line[3] === ' ' || $l === "\t") {
continue;
} elseif (preg_match('/^`(.+?)`/s', $line)) {
continue;
} else {
if (preg_match_all($pattern, $line, $matches)) {
$mentions = array_merge($mentions, $matches[1]);
}
}
}
return array_unique($mentions);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment