Created
September 2, 2013 02:18
-
-
Save noodlehaus/6408702 to your computer and use it in GitHub Desktop.
markdown-like, but not. function for formatting text.
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 | |
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( | |
'@(?:<<)(https?:\/\/[^\s]+)(?:>>)@', | |
function ($m) { | |
return '<img src="'.filter_var($m[1], FILTER_SANITIZE_URL).'">'; | |
}, | |
$text | |
); | |
// text links | |
$text = preg_replace_callback( | |
'@\[(.+)\](?:<)(https?:\/\/[^\s]+)(?:>)@', | |
function ($m) { | |
return ( | |
'<a href="'. | |
filter_var($m[2], FILTER_SANITIZE_URL). | |
'" rel="nofollow">'. | |
$m[1]. | |
'</a>' | |
); | |
}, | |
$text | |
); | |
// urls | |
$text = preg_replace_callback( | |
'@(?:<)(https?:\/\/[^\s]+)(?:>)@', | |
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*>>(.*)@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