PHP Regex with conditions -
i defined log format string this:
[%time%] %logger%.%level%: %message% ${$%context%$}$ $\n$%extra%\n
additionally replacing %-keys want able define conditions near %context%-key:
so if %context% empty, skip complete ${$%context%$}$ if %context% not empty, print prefix { , suffix }
i tried (i planned replace keys within loop):
$output = ''; $subject = '[%time%] %logger%.%level%: %message% ${$%context%$}$ $\n$%extra%\n'; $output .= preg_replace('/(\$(.*|^\$)\$)?%context%(\$(.*|^\$)\$)?/', '\2test\4', $subject);
what expect (context empty):
[%time%] %logger%.%level%: %message% $\n$%extra%\n
what expect (context not empty):
[%time%] %logger%.%level%: %message% {test} $\n$%extra%\n
what (context not empty):
[%time%] %logger%.%level%: %message% {test}$ $\n%extra%\n
and don't know last $ comes from.
here 1 solution - use loop , if-condition solve problem:
$output = ''; $subject = '[%time%] %logger%.%level%: %message% ${$%context%$}$ $\n$%extra%\n'; $replace = array('hello', 'world', ''); $pattern = '/(\${1}([^\$]+)\${1})?%context%(\${1}([^\$]+)\${1})?/'; foreach ($replace $r) { if ($r == '') { $output .= preg_replace($pattern, '', $subject) . '<br>'; } else { $output .= preg_replace($pattern, '$2' . $r . '$4', $subject) . '<br>'; } }
output:
[%time%] %logger%.%level%: %message% {hello} $\n$%extra%\n [%time%] %logger%.%level%: %message% {world} $\n$%extra%\n [%time%] %logger%.%level%: %message% $\n$%extra%\n
Comments
Post a Comment