我需要在php页面中整齐地输出旋转文本。我已经有了{嗨|你好|问候}格式的预双关语文本。我有一个在其他地方找到的php代码,但它不会在句子级别输出旋转文本,其中两个{{来。这是需要修复的代码。
<?php
function spinText($text){
$test = preg_match_all("#'{(.*?)'}#", $text, $out);
if (!$test) return $text;
$toFind = Array();
$toReplace = Array();
foreach($out[0] AS $id => $match){
$choices = explode("|", $out[1][$id]);
$toFind[]=$match;
$toReplace[]=trim($choices[rand(0, count($choices)-1)]);
}
return str_replace($toFind, $toReplace, $text);
}
echo spinText("{Hello|Hi|Greetings}!");;
?>
输出将随机选择单词:Hello或Hi或Greetings。
然而,如果有一个句子级别的旋转,输出就会混乱。例如:
{{hello|hi}.{how're|how are} you|{How's|How is} it going}
输出为
{hello.how're you|How is it going}
正如你所看到的,文本还没有完全旋转。
感谢
这是一个递归问题,所以正则表达式没有那么好;但是递归模式可以帮助:
function bla($s)
{
// first off, find the curly brace patterns (those that are properly balanced)
if (preg_match_all('#'{(((?>[^{}]+)|(?R))*)'}#', $s, $matches, PREG_OFFSET_CAPTURE)) {
// go through the string in reverse order and replace the sections
for ($i = count($matches[0]) - 1; $i >= 0; --$i) {
// we recurse into this function here
$s = substr_replace($s, bla($matches[1][$i][0]), $matches[0][$i][1], strlen($matches[0][$i][0]));
}
}
// once we're done, it should be safe to split on the pipe character
$choices = explode('|', $s);
return $choices[array_rand($choices)];
}
echo bla("{{hello|hi}.{how're|how are} you|{How's|How is} it going}"), "'n";
另请参阅:递归模式