Anonymous user
Execute a Markov algorithm: Difference between revisions
→{{header|PHP}}
Line 3,009:
<lang PHP><?php
function markov($text, $ruleset) {▼
$lines = explode(PHP_EOL, $ruleset);▼
$rules = array();▼
foreach ($lines AS $line) {▼
$spc = "[\t ]+";▼
if (empty($line) OR preg_match('/^#/', $line)) {▼
continue;▼
} elseif (preg_match('/^(.+)' . $spc . '->' . $spc . '(\.?)(.*)$/', $line, $matches)) {▼
list($dummy, $pattern, $terminating, $replacement) = $matches;▼
$rules[] = array(▼
'pattern' => trim($pattern),▼
'terminating' => ($terminating === '.'),▼
'replacement' => trim($replacement),▼
);▼
}▼
}▼
do {▼
$found = false;▼
foreach ($rules AS $rule) {▼
if (strpos($text, $rule['pattern']) !== FALSE) {▼
$text = str_replace($rule['pattern'], $rule['replacement'], $text);▼
if ($rule['terminating']) {▼
return $text;▼
}▼
$found = true;▼
break;▼
}▼
}▼
} while($found);▼
return $text;▼
}▼
$conf = array(
Line 3,119 ⟶ 3,151:
),
);
▲function markov($text, $ruleset) {
▲ $lines = explode(PHP_EOL, $ruleset);
▲ $rules = array();
▲ foreach ($lines AS $line) {
▲ $spc = "[\t ]+";
▲ if (empty($line) OR preg_match('/^#/', $line)) {
▲ continue;
▲ } elseif (preg_match('/^(.+)' . $spc . '->' . $spc . '(\.?)(.*)$/', $line, $matches)) {
▲ list($dummy, $pattern, $terminating, $replacement) = $matches;
▲ $rules[] = array(
▲ 'pattern' => trim($pattern),
▲ 'terminating' => ($terminating === '.'),
▲ 'replacement' => trim($replacement),
▲ );
▲ }
▲ }
▲ do {
▲ $found = false;
▲ foreach ($rules AS $rule) {
▲ if (strpos($text, $rule['pattern']) !== FALSE) {
▲ $text = str_replace($rule['pattern'], $rule['replacement'], $text);
▲ if ($rule['terminating']) {
▲ return $text;
▲ }
▲ $found = true;
▲ break;
▲ }
▲ }
▲ } while($found);
▲ return $text;
▲}
foreach ($conf AS $id => $rule) {
|