I have a string which contains a math formula, like T + ST + s + t …
I’m replacing all those letter identifiers with numbers using:
$ids = array(
'T' => $t1,
'ST', => $st,
's', => $s1,
't', => $t2,
'N', => 1,
);
foreach ($ids as $id => $value) {
if (strpos($formula, $id) !== false) {
$formula = str_replace($id, $value, $formula);
}
}
Which is ok in certain situations.
But if the formula has ST at the beginning I get a string like S345324 ..
I fixed this by moving ST in the first position in my array, but I feel it’s not really the best option 🙂
Are there any other “nicer” solutions?
Are you looking for
strtr()?Note that since
strtr()always tries to find the longest possible match, it won’t replace occurrences ofSTwithS$t1(instead of$st), regardless of how your$replace_pairsarray is ordered.Example (as seen on codepad):
Prints: