我已經編寫了一些代碼來允許在特定數據列上進行計算。用列數據括號替換字符串
例如{1} * {2}會導致第1列乘以第2列。我需要做的是將這些數字替換爲列的實際值。
簡單地說,我需要能夠得到括號內的值,然後像$ column [「括號內的值」]那樣使用它來獲取要插入計算的值。
然後我可以評估字符串。
在此先感謝
我已經編寫了一些代碼來允許在特定數據列上進行計算。用列數據括號替換字符串
例如{1} * {2}會導致第1列乘以第2列。我需要做的是將這些數字替換爲列的實際值。
簡單地說,我需要能夠得到括號內的值,然後像$ column [「括號內的值」]那樣使用它來獲取要插入計算的值。
然後我可以評估字符串。
在此先感謝
像這樣的東西應該工作:
$myString = '{1}*{2}';
$myValues = [1 => '684', 2 => '42'];
$myFormula = preg_replace_callback('{([0-9]+)}', function($match) use ($myValues) {
return $myValues[$match] ?: 'undefined';
}, $myString);
echo "Resulting formula: $myFormula";
可能想給一個更難錯誤時使用一個未定義的指標,但本質上這應該與一些調整工作。
此外,如果您運行比5.4更舊的PHP版本,則需要重寫短陣列語法和lambda。
PHP Rocks !!!
$string = 'blabla bla I want this to be done !!! {10} + {12} Ah the result is awesome but let\'s try something else {32} * {54}';
// Requires PHP 5.3+
$string = preg_replace_callback('/\{(\d+(\.\d+)?)\}\s*([\+\*\/-])\s*\{(\d+(\.\d+)?)\}/', function($m){
return mathOp($m[3], $m[1], $m[4]);
}, $string);
echo $string; // blabla bla I want this to be done !!! 22 Ah the result is awesome but let's try something else 1728
// function from: http://stackoverflow.com/a/15434232
function mathOp($operator, $n1, $n2){
if(!is_numeric($n1) || !is_numeric($n2)){
return 'Error: You must use numbers';
}
switch($operator){
case '+':
return($n1 + $n2);
case '-':
return($n1 - $n2);
case '*':
return($n1 * $n2);
case '/':
if($n2 == 0){
return 'Error: Division by zero';
}else{
return($n1/$n2);
}
default:
return 'Unknown Operator detected';
}
}
「{1} * {2}」在哪裏?只是在某個字符串中?另外,你有嘗試過什麼嗎? – Nick 2013-04-25 08:21:40
您最好將輸入分割開來,而不是像{}那樣用輸入爲1,*,2的方式來爆炸(「,」,$ input),然後您可以簡單地通過結果數組,使用{}引用你的列像$ column [$ array [0]],你將不得不正則表達它我認爲 – Dave 2013-04-25 08:23:03