Last active
November 18, 2023 09:37
-
-
Save chuv1/9641abc8a5a1a9b3bb8c9177fb7ffa9e to your computer and use it in GitHub Desktop.
Test function to convert telegram message entities into HTML markup.
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
public function getHTML($without_cmd = false){ | |
if(empty($this->getEntities())){ | |
return $this->getText($without_cmd); | |
} | |
$text = $this->getText(); | |
$html = ''; | |
$entities_count = \count($this->getEntities())-1; | |
foreach($this->getEntities() as $k => $entity){ | |
if($k === 0){ | |
$html .= mb_substr($text, 0, $entity->getOffset()); | |
} | |
switch($entity->getType()){ | |
default: | |
case 'mention': | |
case 'hashtag': | |
case 'cashtag': | |
case 'bot_command': | |
case 'url': | |
case 'email': | |
case 'phone_number': | |
$html .= mb_substr($text, $entity->getOffset(), $entity->getLength()); | |
break; | |
case 'text_mention': | |
$html .= '<a href="tg://user?id='.$entity->getUser()->getId().'">'.mb_substr($text, $entity->getOffset(), $entity->getLength()).'</a>'; | |
break; | |
case 'text_link': | |
$html .= '<a href="'.$entity->getUrl().'">'.mb_substr($text, $entity->getOffset(), $entity->getLength()).'</a>'; | |
break; | |
case 'bold': | |
$html .= '<b>' . mb_substr($text, $entity->getOffset(), $entity->getLength()) . '</b>'; | |
break; | |
case 'italic': | |
$html .= '<i>' . mb_substr($text, $entity->getOffset(), $entity->getLength()) . '</i>'; | |
break; | |
case 'code': | |
$html .= '<code>' . mb_substr($text, $entity->getOffset(), $entity->getLength()) . '</code>'; | |
break; | |
case 'pre': | |
$html .= '<pre>' . mb_substr($text, $entity->getOffset(), $entity->getLength()) . '</pre>'; | |
break; | |
} | |
if($k === $entities_count){ | |
$html .= mb_substr($text, $entity->getOffset() + $entity->getLength()); | |
} | |
} | |
return $html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Function for @mtproto/core, for parsing messages