Skip to content

Instantly share code, notes, and snippets.

@noodlehaus
Last active December 21, 2015 03:08
Show Gist options
  • Save noodlehaus/d30074850bfaa40cc42b to your computer and use it in GitHub Desktop.
Save noodlehaus/d30074850bfaa40cc42b to your computer and use it in GitHub Desktop.
markdown-like string formatting function
<?php
include './fmt.php';
$text = '';
if (strtolower($_SERVER['REQUEST_METHOD']) === 'post')
$text = $_POST['text'];
?>
<!DOCTYPE html>
<html>
<head>
<title>fmt test</title>
<style>
textarea { width: 500px; height: 200px; }
</style>
</head>
<body>
<pre>
<?= htmlentities(fmt($text)) ?>
</pre>
<div>
<?= fmt($text) ?>
</div>
<form method="post">
<div><textarea name="text"><?= htmlentities($text) ?></textarea></div>
<div><input type="submit"><a href="test.php">Reset</a></div>
</body>
</html>
<?php
function fmt($text) {
$text = htmlentities($text);
// bold
$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(
'@^&gt;&gt;(.*)@m',
function ($m) {
return '<blockquote>'.trim($m[1]).'</blockquote>';
},
$text
)
);
// unordered list
$text = preg_replace(
'@</ul>\s<ul>@m',
'',
preg_replace_callback('@^-(.*)@m', function ($m) {
return '<ul><li>'.trim($m[1]).'</li></ul>';
}, $text)
);
// ordered list
$text = preg_replace(
'@</ol>\s<ol>@m',
'',
preg_replace_callback('@^#(.*)@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 $text;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment