Created
January 6, 2024 17:53
-
-
Save mathiasrw/56e9e9a9c99348e22ff4b5d1359a97df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function spintax($text) { | |
$max = substr_count($text, '}'); | |
$i = 0; | |
$currentPos = 0; | |
while ($currentPos < strlen($text) && ($endPos = strpos($text, '}', $currentPos)) !== false) { | |
if ($i++ > $max) break; | |
// Find the matching opening brace. | |
$startPos = strrpos(substr($text, 0, $endPos), '{'); | |
// Skip if there's no matching opening brace and update the current position. | |
if ($startPos === false) { | |
$currentPos = $endPos + 1; | |
continue; | |
} | |
$length = $endPos - $startPos + 1; | |
// Extract the spintax string | |
$spintaxString = substr($text, $startPos, $length); | |
$options = explode('|', trim($spintaxString, '{}')); | |
// Skip if not spintax | |
if (count($options) == 1) { | |
$currentPos = $endPos + 1; | |
continue; | |
} | |
// Pick option | |
$randomChoice = $options[array_rand($options)]; | |
$text = substr_replace($text, $randomChoice, $startPos, $length); | |
$currentPos = $startPos + strlen($randomChoice); | |
} | |
return $text; | |
} | |
function runTest() { | |
$testCases = [ | |
"This is a {simple|basic|plain} test of.", | |
"Nested {example|test with {inner|deep {1|2|3}} values}.", | |
"More {complex|challenging} example: {a|b|c is {d|e|f}|g}.", | |
"Another one {here|there {now|then {quickly|slowly}}|everywhere}.", | |
"{First|1st} level {with|and {second|2nd} level {including|with {third|3rd} level}}.", | |
"This is my {{{handlebar}}}.", | |
"This is my {{{handle|bar}}}.", | |
"This is a is } my {handle|bar}." | |
]; | |
foreach ($testCases as $testCase) { | |
echo "Input: " . $testCase . "\n"; | |
echo "Output: " . spintax($testCase) . "\n\n"; | |
} | |
} | |
// runTest(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment