我有一个字符串
The expression (a + b + c)^2 - (a + b - c)^2 + (a - b + c)^2 + ( b + c - a)^2
如何将^ 2转换为 2
<p>The expression (a + b + c)<sup>2</sup> + (a + b - c)<sup>2</sup> + (a - b + c)<sup>2</sup> + ( b + c - a)<sup>2</sup> + equals ________</p>
使用html还是php?
答案 0 :(得分:3)
preg_replace
是你的朋友:
$str = "The expression (a + b + c)^2 - (a + b - c)^2 + (a - b + c)^2 + ( b + c - a)^2";
echo preg_replace("/\^([^\s]+)/","<sup>$1</sup>", $str);
结果是表达式(a + b + c) 2 - (a + b - c) 2 +(a - b + c) 2 +(b + c - a) 2
\^([^\s]+)
模式匹配^
及其后的所有内容,直到遇到空格。因此1^0.99
将更改为1 0.99 ,(a+b)^(c+d)
将变为(a + b)(c + d)甚至{{1}将转换为hello banana 。
答案 1 :(得分:1)
您可以在PHP中使用正则表达式来替换模式:
<?php
$msg = '(a + b + c)^2 - (a + b - c)^2 + (a - b + c)^2 + ( b + c - a)^2';
$msg = preg_replace('#\^([0-9]+)#','<sup>$1</sup>',$msg);
echo $msg;
?>
这将写下以下内容:
(a + b + c)<sup>2</sup> - (a + b - c)<sup>2</sup> + (a - b + c)<sup>2</sup> + ( b + c - a)<sup>2</sup>