日期:2014-05-17  浏览次数:20397 次

字符串中的 字符替换
我现在有一些如这样的字符串

[3]/([2]*[2])

其中[3] [2] 分别对应我系统里的3号和2号变量 $e3 和$e2

希望将上面的式子通过程序转换成如下字符串

$e3/($e2*$e2)

这样就可以用eval计算了。

请问如何实现这个转换?有什么方法。



------解决方案--------------------
<?php
$str='[3]/([2]*[2])';
for($i=1;$i<=100;$i++){
$str=str_replace('['.$i.']', '$e'.$i, $str);
}
echo $str;
?>
------解决方案--------------------
C/C++ code

$str = '[3]/([2]*[2])';
echo procnum($str);
function procnum($str){
    //$i = 0;
    while (preg_match('/(\[\d+\])/',$str)){
        $str = preg_replace('/\[(\d+)\]/',"\$e\$1",$str,1);
    //    if($i++>100) break;
    }
    return $str;
}