mathceleb

03-03-2010, 08:42 PM

I'm looking for a function to replace instances of a carrot and a number to superscript. Currently, I have a function that handles positive powers below:

function polyformal($tt)

{

// replace all ^ & numbers(0-9) & ("+" or "-" or ")") with sup numbers with

for ($x=80;$x>=0;$x--)

{

$tt=str_replace("^" . $x . "+","<sup>" . $x . "</sup>+",$tt);

$tt=str_replace("^" . $x . "-","<sup>" . $x . "</sup>-",$tt);

$tt=str_replace("^" . $x . ")","<sup>" . $x . "</sup>)",$tt);

$tt=str_replace("^" . $x,"<sup>" . $x . "</sup>",$tt);

}

return $tt;

}

I want to use preg_replace if possible to be more efficient as well as to account for any power positive or negative without having to do a large loop. I tried this below:

$tt="4(2ax^7y^6z^3-6x^3y^4z^-825)^5";

$tt=preg_replace('#[0-9]#','<sup>' . '#[0-9]#' . '</sup>',$tt);

This replaces all indidual numbers with the superscript #[0-9]#, but replaces each digit of 825 with a replacement.

My goal is to make numbers raised to a power superscript. Any ideas?

function polyformal($tt)

{

// replace all ^ & numbers(0-9) & ("+" or "-" or ")") with sup numbers with

for ($x=80;$x>=0;$x--)

{

$tt=str_replace("^" . $x . "+","<sup>" . $x . "</sup>+",$tt);

$tt=str_replace("^" . $x . "-","<sup>" . $x . "</sup>-",$tt);

$tt=str_replace("^" . $x . ")","<sup>" . $x . "</sup>)",$tt);

$tt=str_replace("^" . $x,"<sup>" . $x . "</sup>",$tt);

}

return $tt;

}

I want to use preg_replace if possible to be more efficient as well as to account for any power positive or negative without having to do a large loop. I tried this below:

$tt="4(2ax^7y^6z^3-6x^3y^4z^-825)^5";

$tt=preg_replace('#[0-9]#','<sup>' . '#[0-9]#' . '</sup>',$tt);

This replaces all indidual numbers with the superscript #[0-9]#, but replaces each digit of 825 with a replacement.

My goal is to make numbers raised to a power superscript. Any ideas?