http://ronaldarichardson.com/2011/09/23/recursive-php-spintax-class-3-0/
我喜欢这个剧本,但并不完美。如果使用此测试输入用例:
{这是我的{spintax\spuntext}格式化字符串、我的{spintax\spuntext}格式化字符串、我的{spintax_spuntext}格式化字符串示例。}
您可以看到,结果总是包含3个重复的"spuntext“或”spuntext“。例如,它从来不包含1个"spuntext“和2个”spuntext“。
示例:
这是我的spuntext格式化字符串,我的spuntext格式化字符串,我的spuntext格式化字符串示例。
要成为真正的随机块,需要为每个spintax {AC.26}块生成一个随机迭代,而不是对相同的块重复相同的选择,例如{spintax spuntext}。
如果您查看页面上的注释7,fransberns就会出现在某些东西上,但是当在活动环境中使用他修改过的代码时,脚本会在无限循环中重复运行,并消耗掉所有服务器内存。所以那里肯定有个窃听器,但我不知道是什么。
有什么想法吗?或者,有人知道有一个健壮的PHP spintax脚本,它允许嵌套的spintax,并且确实是随机的吗?
发布于 2012-08-07 14:16:49
请检查这个要旨,它正在工作(它比原始代码简单得多..)。
发布于 2012-08-07 14:38:30
Spintax类用相同的随机选择选项替换所有实例{spintax spuntext}的原因是由于该类中的这一行:
$str = str_replace($match[0], $new_str, $str);str_replace函数用搜索字符串中的替换替换子字符串的所有实例。为了只替换第一个实例(按您的需要以串行方式进行),我们需要使用传递的"count“参数1的函数preg_replace。但是,当我查看Spintax的你的链接和引用post #7时,我注意到了他建议的对Spintax的扩展中的一个错误。
兄弟会建议取代:
$str = str_replace($match[0], $new_str, $str);在这方面:
//one match at a time
$match_0 = str_replace("|", "\|", $match[0]);
$match_0 = str_replace("{", "\{", $match_0);
$match_0 = str_replace("}", "\}", $match_0);
$reg_exp = "/".$match_0."/";
$str = preg_replace($reg_exp, $new_str, $str, 1);fransbergs的建议的问题是,在他的代码中,他没有正确地构造preg_replace函数的正则表达式。他的错误来自于没有正确转义\字符。他的替换代码应该是这样的:
//one match at a time
$match_0 = str_replace("|", "\\|", $match[0]);
$match_0 = str_replace("{", "\\{", $match_0);
$match_0 = str_replace("}", "\\}", $match_0);
$reg_exp = "/".$match_0."/";
$str = preg_replace($reg_exp, $new_str, $str, 1);考虑用这个增广版本替换原来的类,利用我对fransberns建议的替换网的更正:
class Spintax {
function spin($str, $test=false)
{
if(!$test){
do {
$str = $this->regex($str);
} while ($this->complete($str));
return $str;
} else {
do {
echo "<b>PROCESS: </b>";var_dump($str = $this->regex($str));echo "<br><br>";
} while ($this->complete($str));
return false;
}
}
function regex($str)
{
preg_match("/{[^{}]+?}/", $str, $match);
// Now spin the first captured string
$attack = explode("|", $match[0]);
$new_str = preg_replace("/[{}]/", "", $attack[rand(0,(count($attack)-1))]);
// $str = str_replace($match[0], $new_str, $str); //this line was replaced
$match_0 = str_replace("|", "\\|", $match[0]);
$match_0 = str_replace("{", "\\{", $match_0);
$match_0 = str_replace("}", "\\}", $match_0);
$reg_exp = "/".$match_0."/";
$str = preg_replace($reg_exp, $new_str, $str, 1);
return $str;
}
function complete($str)
{
$complete = preg_match("/{[^{}]+?}/", $str, $match);
return $complete;
}
}当我尝试使用fransberns的建议替换“原样”时,由于\字符转义不当,我得到了一个无限循环。我想这就是你记忆问题的根源。在更正了fransberns建议的用\字符的正确转义替换后,我没有进入无限循环。
尝试上面的类并进行修正后的增强,看看它是否在您的服务器上工作(我看不出为什么它不应该工作)。
https://stackoverflow.com/questions/11804093
复制相似问题