Last active
February 6, 2023 20:18
-
-
Save ShNURoK42/b5ce8baa570975db487c to your computer and use it in GitHub Desktop.
Mention for Parsedown
This file contains hidden or 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 | |
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
Works great thank you 👍