- strtr: documentation ( source)
- preg_match_all: documentation ( source)
<?php
$str = 'Showing results [program=for {program} programs|No pogram at all] [province=in {province}] [degree=with degree of {degree}]';
function interpolateString($message, array $context = array()) {
$replace = array();
foreach ($context as $key => $val) {
$replace['{' . $key . '}'] = $val;
}
return strtr($message, $replace);
}
$arrContext = array(
'program' => false,
'province' => 'Ontario',
'degree' => false
);
//echo interpolateString($str, $arrContext);
echo "\n";
$arrMatches = array();
preg_match_all("/\[(\w+)\=([^\[\]\|.*]*)?\|*([^\[\].*]*)\]/", $str, $arrMatches);
$contextKeys = $arrMatches[1];
$contextCondition = array();
$contextValues = array();
$i = 0;
foreach ($contextKeys as $key){ $contextCondition += array($key => $arrMatches[0][$i]); $i++;}
$i = 0;
foreach ($contextKeys as $key){ $value = $arrContext[$key] != false ? 2 : 3; $contextValues += array($key => $arrMatches[$value][$i]); $i++;}
foreach ($contextKeys as $key){
echo "{$key} -> {$contextCondition[$key]} -> {$contextValues[$key]}\n";
}