Skip to content

Instantly share code, notes, and snippets.

@jakebathman
Forked from bmcculley/markov.php
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakebathman/11d0e0a2cd8693584905 to your computer and use it in GitHub Desktop.
Save jakebathman/11d0e0a2cd8693584905 to your computer and use it in GitHub Desktop.
PHP Markov Chain class
<?php
/*
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
bug.
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();
$tmp->makeList($string);
$tmp->buildTree();
// :: phraseWriter(YOURSEEDWORD, NUMBEROFWORDSINRESULTSOUTPUT)
print $tmp->phraseWriter('markov', 10);
------------------
Written by Levi Thornton at Boogybonbon.com, 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 http://www.boogybonbon.com/, or do yourself a favor
and get a subscription to Wordze.com 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]);
next($this->wordList);
$ns++;
}
}
function phraseWriter($seed, $words) {
$results = $seed = strtolower($seed);
if($this->termTree[$seed]) {
while($nntermTree[$seed]){
if($this->termTree[$seed][$rndseed]) {
$results .= ' '.$this->termTree[$seed][$rndseed];
$seed = $this->termTree[$seed][$rndseed];
$nn++;
}
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