<?php
function renderBlock(array $m) {
$callable = "build$m[1]";
return function_exists($callable)
? $callable($m[2] ?? '')
: $m[0];
}
function buildPiechart(string $payloadString) {
$values = [
'angle' => 0,
'colorset' => 'red',
'stroke' => 1,
'value' => 1
];
$rules = [
'angle' => '/\d+/',
'colorset' => '/reds|yellows|blues/i',
'stroke' => '/\d+/',
'value' => '/\d+/',
];
$attributes = preg_split(
'/\h+/u',
$payloadString,
0,
PREG_SPLIT_NO_EMPTY
);
foreach ($attributes as $pair) {
[$key, $value] = explode(':', $pair, 2);
if (
key_exists($key, $values)
&& preg_match($rules[$key], $value, $m)
) {
$values[$key] = $m[0];
}
}
return sprintf(
'<pie a="%s" c="%s" s="%s" v="%s">',
...array_values($values)
);
}
$text = 'here is a block to be replaced [block:piechart value:25 angle:0] [block] and [block:notcoded attr:val] another one [block:piechart colorset:reds value:20]';
echo preg_replace_callback(
'/\[block:([a-z]+)\h*([^\]\r\n]*)\]/u',
'renderBlock',
$text
);
preferences:
25.91 ms | 411 KiB | 5 Q