...

View Full Version : preg_replace ^ and [-100-100]



mathceleb
03-03-2010, 09: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?

kbluhm
03-03-2010, 09:50 PM
$text = preg_replace( '/\^(\d+)/', '<sup>$1</sup>', $text );

mathceleb
03-03-2010, 09:53 PM
$text = preg_replace( '/\^(\d+)/', '<sup>$1</sup>', $text );



kbluhm,

That did all positive powers, which is a great start. But it left the negative powers unchanged.

Thanks for that portion. Any ideas on the negative power portion?

JordanW
03-03-2010, 09:56 PM
$tt=preg_replace('/\^(-?)(\d+)/','<sup>$1$2</sup>',$tt);

mathceleb
03-03-2010, 10:03 PM
$tt=preg_replace('/\^(-?)(\d+)/','<sup>$1$2</sup>',$tt);

That's fantastic, thanks Jordan W!

I've been relying on str_replace as a crutch for too long and I need to read up more on regular expressions.

JordanW
03-03-2010, 10:12 PM
Literally what I did the other week. As soon as you get the hang of it... you just cannot stop using it!

Here is a great little tool for your reference:
http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet-version-1/

kbluhm
03-03-2010, 10:38 PM
kbluhm,

That did all positive powers, which is a great start. But it left the negative powers unchanged.

Thanks for that portion. Any ideas on the negative power portion?

Oops, over read that portion. Sorry about that.


$text = preg_replace( '/\^(\-?\d+)/', '<sup>$1</sup>', $text );



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum