Skip to content

Instantly share code, notes, and snippets.



Forked from bmcculley/markov.php
Last active Aug 29, 2015
What would you like to do?
PHP Markov Chain class
Levi Thornton from boogybonbon and wordze generously posted his php Markov
Chain class.. unfortunately there is a missing $nn++ thus the class can hang,
the working version is below all credit to Levi for the code, i just fixed a
Example Usage:
$string = "The more words you have the better this markov script will run and
produce more unique results on your output. Best of luck and as always enjoy!
~ Levi";
$tmp = new clsMarkov();
print $tmp->phraseWriter('markov', 10);
Written by Levi Thornton at, All rights reserved, so don't
even think about removing my credit line, and trying to pass it off as if you
wrote it!
You can use this script for free in your own scripts, you can NOT resell it,
OR bundle it with any other free or paid packages. I if you want to toss me a
bone, give me a link at, or do yourself a favor
and get a subscription to and support the global project for better
keyword research and development!
class clsMarkov {
var $wordList= array();
var $termTree = array();
function makeList($string) {
$string = strtolower($string);
$string = preg_replace("/[^A-z0-9\s]/i", "", $string);
preg_match_all("/[A-z0-9]+\S/", $string, $op);
$this->wordList = $op[0];
return $this->wordList;
function buildTree() {
// $searchList = $this->wordList;
$arraySize = count($this->wordList);
while ($ns!=$arraySize) {
$termRoot = current($this->wordList);
$termKeys = array_keys($this->wordList,$termRoot);
foreach ($termKeys as $key=>$num) {
$this->termTree[$termRoot][] = $this->wordList[($num+1)];
$this->termTree[$termRoot] = array_unique($this->termTree[$termRoot]);
function phraseWriter($seed, $words) {
$results = $seed = strtolower($seed);
if($this->termTree[$seed]) {
if($this->termTree[$seed][$rndseed]) {
$results .= ' '.$this->termTree[$seed][$rndseed];
$seed = $this->termTree[$seed][$rndseed];
else $nn++;
return $results;
} else return 'No seed match';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment