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

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -