Created
November 6, 2015 10:10
-
-
Save siamkreative/0098993097bdf5cea5da to your computer and use it in GitHub Desktop.
Convert HTML string to Slack's own markup language (https://slack.zendesk.com/hc/en-us/articles/202288908-Formatting-your-messages)
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 | |
/* Strip out un-supported HTML tags */ | |
$content = strip_tags($content, '<strong><em><del><li><code><pre>'); | |
/* Properly format message */ | |
$content = str_replace(array('<strong>', '</strong>'), array('*', '*'), $content); | |
$content = str_replace(array('<em>', '</em>'), array('_', '_'), $content); | |
$content = str_replace(array('<del>', '</del>'), array('~', '~'), $content); | |
$content = str_replace(array('<li>', '</li>'), array('•', ''), $content); | |
$content = str_replace(array('<code>', '</code>'), array('`', '`'), $content); | |
$content = str_replace(array('<pre>', '</pre>'), array('```', '```'), $content); | |
?> |
Thank you dami95 for your contribution. I have updated your preg_match_all for links to support additional params before and after the href
param. I also moved the linkCount
out of the for loop so it follows PHP 8 standards.
/* Strip out un-supported HTML tags */
$content = strip_tags($content, '<br><strong><em><del><li><code><pre><a></a>');
/* Properly format message */
$content = str_replace(array('<br />', '<br>'), "\n", $content);
$content = str_replace(array('<strong>', '</strong>'), array('*', '*'), $content);
$content = str_replace(array('<em>', '</em>'), array('_', '_'), $content);
$content = str_replace(array('<del>', '</del>'), array('~', '~'), $content);
$content = str_replace(array('<li>', '</li>'), array('•', ''), $content);
$content = str_replace(array('<code>', '</code>'), array('`', '`'), $content);
$content = str_replace(array('<pre>', '</pre>'), array('```', '```'), $content);
/* Process Links and convert to markdown style */
preg_match_all('/<a.*href=\"([^"]*?)\".*>([^"]*?)<\/a>/i', $content, $res);
$linkCount = count($res[0]);
for ($i = 0; $i < $linkCount; $i++) {
$content = str_replace($res[0][$i], '<'.$res[1][$i].'|'.$res[2][$i].'>', $content);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, thank you for your code, I add handling html links to slack and brs into \n.
Enjoy ;)