Skip to content

Instantly share code, notes, and snippets.

@mattattui
Created December 16, 2011 12:06
Show Gist options
  • Save mattattui/1485812 to your computer and use it in GitHub Desktop.
Save mattattui/1485812 to your computer and use it in GitHub Desktop.
Generate fake text with optional paragraphs and html
<?php
function lorem($length = 5, $paragraphs = false, $html = false)
{
$corpus = array('ad', 'adipisicing', 'aliqua', 'aliquip', 'amet', 'anim', 'aute', 'cillum', 'commodo', 'consectetur', 'consequat', 'culpa', 'cupidatat', 'deserunt', 'do', 'dolor', 'dolore', 'duis', 'ea', 'eiusmod', 'elit', 'enim', 'esse', 'est', 'et', 'eu', 'ex', 'excepteur', 'exercitation', 'fugiat', 'id', 'in', 'incididunt', 'ipsum', 'irure', 'labore', 'laboris', 'laborum', 'lorem', 'magna', 'minim', 'mollit', 'nisi', 'non', 'nostrud', 'nulla', 'occaecat', 'officia', 'pariatur', 'proident', 'qui', 'quis', 'reprehenderit', 'sed', 'sint', 'sit', 'sunt', 'tempor', 'ullamco', 'ut', 'velit', 'veniam', 'voluptate');
// If HTML tag given, figure out the closing tag
$open_tag = $closing_tag = false;
if ($html)
{
$open_tag = $html;
if (preg_match('/^<([a-z]+)/i', $open_tag, $matches))
{
$closing_tag = sprintf('</%s>', $matches[1]);
} else {
throw new Exception('Couldn\'t derive closing tag. Bad input?');
}
}
// Expand corpus size to fit requested length
while (count($corpus) < $length)
{
$corpus = array_merge($corpus, $corpus);
}
if ($length > 1)
{
$keys = array_rand($corpus, $length - 1);
$out = array('Lorem');
foreach($keys as $idx => $k)
{
if (mt_rand(1,15) == 1)
{
$out[] = '. '.ucfirst($corpus[$k]);
}
elseif (mt_rand(1,12) == 1)
{
$out[] = ', '.$corpus[$k];
} else {
$out[] = $corpus[$k];
}
}
$out = ($html ? $open_tag : '') . str_replace(array(' .', ' ,'), array('.', ','), join($out, ' ').'.') . ($html ? $closing_tag : '');
if ($paragraphs) {
$out = preg_replace_callback('/\. /', function($matches) use ($html, $open_tag, $closing_tag){
static $dotcount = 0;
static $paralength = null;
if (!$paralength)
{
$paralength = mt_rand(5,7);
}
if ((++$dotcount % $paralength) == 0)
{
return $matches[0].($html ? $closing_tag.PHP_EOL.PHP_EOL.$open_tag : PHP_EOL.PHP_EOL);
}
else
{
return $matches[0];
}
}, $out);
}
return $out;
}
else
{
return $html ? sprintf('%sLorem%s', $open_tag, $closing_tag) : 'Lorem.';
}
}
/* Self-test */
if (basename($_SERVER['SCRIPT_NAME']) == basename(__FILE__))
{
$length = isset($_SERVER['argv'][1]) ? intval($_SERVER['argv'][1]) : 40;
echo lorem($length, true, '<p class="lorem">').PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment