<?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
);
- Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
- here is a block to be replaced <pie a="0" c="red" s="1" v="25"> [block] and [block:notcoded attr:val] another one <pie a="0" c="reds" s="1" v="20">
preferences:
112.57 ms | 407 KiB | 5 Q