Topic: PHP problem - functions within regex
I have the following PHP function which I use to roll a dice using the d20 format (2d6+2 for example) for describing the role.
function dice($rollwhat) {
$ex = explode("d",$rollwhat);
$diceroll = 0;
if (eregi("\+",$rollwhat)) {
$ex2 = explode("+",$ex[1]);
for ($i = 1; $i <= $ex[0]; $i++) {
$diceroll = round($diceroll + rand(1,$ex2[0]));
}
$result = round($diceroll + $ex2[1]);
} elseif (eregi("-",$rollwhat)) {
$ex2 = explode("-",$ex[1]);
for ($i = 1; $i <= 10; $i++) {
$diceroll = round($diceroll + rand(1,$ex2[0]));
}
$result = round($diceroll - $ex2[1]);
} elseif (eregi("%",$rollwhat) || eregi("100",$rollwhat)) {
$ex[1] = str_replace("%","",$ex[1]);
if (eregi("\+",$rollwhat)) {
$ex2 = explode("-",$ex[1]);
for ($i = 1; $i <= $ex[0]; $i++) {
$dice1 = rand(0,9);
$dice2 = rand(0,9);
$combine_rolls = $dice1."".$dice2;
if ($combine_rolls==00) $rolled = 100;
else $rolled = $combine_rolls;
$diceroll = round($diceroll + $rolled);
}
$result = round($diceroll + $ex2[1]);
} elseif (eregi("-",$rollwhat)) {
$ex2 = explode("-",$ex[1]);
for ($i = 1; $i <= 10; $i++) {
$dice1 = rand(0,9);
$dice2 = rand(0,9);
$combine_rolls = $dice1."".$dice2;
if ($combine_rolls==00) $rolled = 100;
else $rolled = $combine_rolls;
$diceroll = round($diceroll + $rolled);
}
$result = round($diceroll - $ex2[1]);
} else {
for ($i = 1; $i <= $ex[0]; $i++) {
$dice1 = rand(0,9);
$dice2 = rand(0,9);
$combine_rolls = $dice1."".$dice2;
if ($combine_rolls==00) $rolled = 100;
else $rolled = $combine_rolls;
$diceroll = round($diceroll + $rolled);
}
$result = round($diceroll);
}
} else {
for ($i = 1; $i <= $ex[0]; $i++) {
$diceroll = round($diceroll + rand(1,$ex[1]));
}
$result = round($diceroll);
}
return $rollwhat." = ".$result;
}
The function works as expected when I call it using:
<?php
// function seen above here
echo dice("2d9+9"); //returns: 2d9+9 = the result of the role
?>
The problem I'm having results when attempting to implement it as BBcode within PunBB.
I have added the function dice to the functions.php file in the include directory.
I have added the following code to post.php aswell as the parse_message function as I don't want the dice rerolling everytime someone refreshs the page. It is before the SQL query to add messages to the database.
$message = preg_replace('#\[diceroll\](.*?)\[/diceroll\]#s',dice('$1'),$message);
My problem is that the result for the dice roll is always 0 which is impossible to roll as seen in the function.
As I mentioned earlier, calling the function with echo dice("1d6+2"); works correctly.
Why is this happening and how can I fix it?
Thanks in advance.