Skip to content

Instantly share code, notes, and snippets.

@choult
Last active August 3, 2016 12:48
Show Gist options
  • Save choult/c0c0950a033e19ae43c146c800ac1865 to your computer and use it in GitHub Desktop.
Save choult/c0c0950a033e19ae43c146c800ac1865 to your computer and use it in GitHub Desktop.
Source code to generate random Daily Mail headlines from a JSON file of real DM headlines
<?php
class Word
{
private $word = '';
private $links = [];
public function __construct($word) {
$this->word = $word;
}
public function __toString() {
return $this->word;
}
public function addLink(Word $word) {
$this->links[] = $word;
}
public function getNext()
{
$pos = rand(0, count($this->links) - 1);
return $this->links[$pos];
}
}
class WordFactory
{
private $words = [];
public function get($word) {
if (!isset($this->words[$word])) {
$this->words[$word] = new Word($word);
}
return $this->words[$word];
}
}
class End extends Word
{
public function __construct() {}
}
class Start extends Word
{
public function __construct() {}
}
$s = new Start();
$e = new End();
$f = new WordFactory();
function c($s, $e, $f, $str) {
$current = $s;
foreach (explode(" ", $str) as $word) {
if (trim($word)) {
$word = $f->get($word);
$current->addLink($word);
$current = $word;
}
}
$current->addLink($e);
}
$fname = __DIR__ . '/dmheadlines.json';
$cont = json_decode(file_get_contents($fname), true);
foreach ($cont as $str) {
c($s, $e, $f, $str);
}
$current = $s;
$words = [];
while ($current !== $e) {
$words[] = $current;
$current = $current->getNext();
}
$key = array_rand($cont);
$real = strtoupper($cont[$key]);
$fake = strtoupper(trim(implode(' ', $words))) . "\n";
$arr = [$real, $fake];
shuffle($arr);
header('Content-type: text/html');
?><html><head><title>Daily Mail Headline Generator</title></head><body><h1 style="float: left; clear: both; margin-bottom: 20px; width: 100%;">Which is the real Daily Mail headline?</h1>
<div style="width: 300px; float: left; clear: none;"><h2><?php echo $arr[0]; ?></h2></div>
<div style="width: 100px; float: left; clear; none; text-align: center;"><h3>or</h3></div>
<div style="width: 300px; float: left; clear: none;"><h2><?php echo $arr[1]; ?></h2></div>
<form action="/dm" method="GET" style="float: left; clear: both; width: 700px; text-align: center;"><input type="submit" value="Another" /></form></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment