jakebathman
7/28/2015 - 1:39 AM

PHP Markov Chain class

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';
	}
}
?>