I've the following code:
$formula = "E1 + E2 + E4 + E5 + E7 + E8 + E10 + E11";
$patterns = array('Se' => '@Se@',
'Et' => '@Et@',
'E1' => '@E1@',
'E2' => '@E2@');
$values = array('Se' => 9,
'Et' => 12,
'E1' => 1,
'E2' => 8);
$replaced = preg_replace($patterns, $values, $formula);
echo $replaced;
"1 + 8 + E4 + E5 + E7 + E8 + 10 + 11"
I need a code that only replace E1, and ignore E10 and E11, in this case showing the following result: "1 + 8 + E4 + E5 + E7 + E8 + E10 + E11"
thanks!
<?php
$formula = "E1 + E2 + E4 + E5 + E7 + E8 + E10 + E11";
$patterns = array('@\bSe\b@',
'@\bEt\b@',
'@\bE1\b@',
'@\bE2\b@');
$values = array(9, 12, 1, 8);
$replaced = preg_replace($patterns, $values, $formula);
echo $replaced;
Outputs:
1 + 8 + E4 + E5 + E7 + E8 + E10 + E11
Edit. Your code refactored for better reading:
<?php
$formula = "E1 + E2 + E4 + E5 + E7 + E8 + E10 + E11";
$map = array(
'Se' => 9,
'Et' => 12,
'E1' => 1,
'E2' => 8,
);
$patterns = array_keys($map);
$patterns = array_map(function ($v) { return "/\b$v\b/"; }, $patterns);
$values = array_values($map);
$replaced = preg_replace($patterns, $values, $formula);
echo $replaced;
you can use this pattern
"/E1[^0-9]/"
An other way with to do it:
$values = array('Se' => 9,
'Et' => 12,
'E1' => 1,
'E2' => 8);
$formula = "E1 + E2 + E4 + E5 + E7 + E8 + E10 + E11";
$formulaArray = preg_split('~\b~', $formula);
$formula = array_reduce($formulaArray, function ($c, $i) use ($values) {
return $c . (isset($values[$i]) ? $values[$i] : $i);
});
The main interest of this approach is that your string is parsed only once (instead of once per pattern).