2019-04-29, 18:50:02
(2019-04-26, 02:46:42)shawn_a Wrote: This is what I wrote to do this
PHP Code:function getExpansion($trigger,$contents,$noargs = false){
// todo: get lookaheads and lookbehind implemented so you can put non executing code in pages for examples.
// $lookb = "<code>";
// $looka = "</code>";
// $pattern = "/(?<!".$lookb.")\(%\s*(".$trigger.")(\s+(?:%[^%\)]|[^%])+)?\s*%\)(?!".$looka.")/";
// $pattern = "/(?<=".$look.")\(%\s*(".$trigger.")(\s+(?:%[^%\)]|[^%])+)?\s*%\)(?=".$look.")/";
$pattern = "/\(%\s*(".$trigger.")(\s+(?:%[^%\)]|[^%])+)?\s*%\)/";
if(preg_match($pattern,$contents,$matches)){
# echo "<h2>Trigger was Found</h2>"; print_r($matches);
if(!empty($matches[2]) && !$noargs){
// get arguments
# echo "<h2>Trigger has arguments</h2>";
return array(true,'args'=>get_args(trim($matches[2])) );
}
else
{
return array(true);
}
}
}
function get_args($str){
/*
Gets key value pairs from a string
pairs are deimited by space
values can be defined as either
key=value_no_spaces
key='value spaces'
key = "value spaces"
key
* spaces in the pair assigment do not matter
*/
// TODO: make delimiters variable
$regex = <<<EOD
/(?J)(?:(?P<key>\w+)\s*\=\s*["'](?P<value>[^"']*(?:["']{2}[^"']*)*)["']) | (?:(?P<key>\w+)\s*\=\s*(?<value>[^"'\s]*)) | (?:(?P<key>\w+)\s*)/ix
EOD;
$args = Array();
preg_match_all($regex,$str,$argsraw,PREG_SET_ORDER);
if($argsraw){
$cnt = count($argsraw);
for($i=0;$i<$cnt;$i++){
# echo $argsraw[$i]['key'] . " = " . $argsraw[$i]['value'] . "<br>";
$args[strtolower($argsraw[$i]['key'])] = $argsraw[$i]['value'];
}
}
return $args;
}
Nice one. I have to admit that even after several years coding, I still don't utilise REGEX half as much as I should.