Skip to content

Instantly share code, notes, and snippets.

@noodlehaus
Created September 2, 2013 02:18
Show Gist options
  • Save noodlehaus/6408702 to your computer and use it in GitHub Desktop.
Save noodlehaus/6408702 to your computer and use it in GitHub Desktop.
markdown-like, but not. function for formatting text.
<?php
function nomad($text) {
$text = htmlentities($text);
// strong
$text = preg_replace_callback('@\*(.+)\*@U', function ($m) {
return '<strong>'.trim($m[1]).'</strong>';
}, $text);
// images
$text = preg_replace_callback(
'@(?:&lt;&lt;)(https?:\/\/[^\s]+)(?:&gt;&gt;)@',
function ($m) {
return '<img src="'.filter_var($m[1], FILTER_SANITIZE_URL).'">';
},
$text
);
// text links
$text = preg_replace_callback(
'@\[(.+)\](?:&lt;)(https?:\/\/[^\s]+)(?:&gt;)@',
function ($m) {
return (
'<a href="'.
filter_var($m[2], FILTER_SANITIZE_URL).
'" rel="nofollow">'.
$m[1].
'</a>'
);
},
$text
);
// urls
$text = preg_replace_callback(
'@(?:&lt;)(https?:\/\/[^\s]+)(?:&gt;)@',
function ($m) {
return (
'<a href="'.
filter_var($m[1], FILTER_SANITIZE_URL).
'" rel="nofollow">'.
$m[1].
'</a>'
);
},
$text
);
// blockquote
$text = preg_replace(
'@</blockquote>\s<blockquote>@m',
' ',
preg_replace_callback(
'@^\s*&gt;&gt;(.*)@m',
function ($m) {
return '<blockquote>'.trim($m[1]).'</blockquote>';
},
$text
)
);
// unordered list
$text = preg_replace(
'@</ul>\s<ul>@m',
'',
preg_replace_callback('@^\s*-(.*)@m', function ($m) {
return '<ul><li>'.trim($m[1]).'</li></ul>';
}, $text)
);
// ordered list
$text = preg_replace(
'@</ol>\s<ol>@m',
'',
preg_replace_callback('@^\s*#(.*)@m', function ($m) {
return '<ol><li>'.trim($m[1]).'</li></ol>';
}, $text)
);
// paragraph
$text = preg_replace_callback('@^(.+)(\r?\n)?@m', function ($m) {
$line = trim($m[1]);
return (strlen($line) ? '<p>'.$line.'</p>' : '');
}, $text);
// remove incorrect nesting
$text = preg_replace('@<p><(ol|ul|blockquote)>@', '<\\1>', $text);
$text = preg_replace('@</(ol|ul|blockquote)></p>@', '</\\1>', $text);
return trim($text);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment