<?php
$str = 'IF(1>10, "Large", "Medium")
IF(1>10, IF(44>20, "Large", "Medium"), "Small")
IF(1>10, IF(44>20, "Large", IF(4<5, "Tiny", "Medium")), "Small")
IF(A1>10, IF(A1>20, "Large", IF(A1<5, "Tiny", "Medium")), "Small")';
$pattern =<<<'REGEX'
~
# subpatterns
(?<string> " [^"\\]*+ (?s: \\. [^"\\]* )*+ " ){0}
(?<nparens> \( [^"()]*+ (?: \g<string> [^"()]* | \g<nparens> [^"()]* )*+ \) ){0}
(?<other> [^"()\s,] (?: [^"(),]* [^"()\s,])? ){0}
(?<part> (?: \g<string> | \g<nparens> | \g<other> )* ){0}
# main pattern
IF\( \s* (\g<part>) \s* , \s* (\g<part>) \s*, \s* (\g<part>) \s* \)
~x
REGEX;
//$replacement = '($7) ? ($8) : ($9)';
$replacement = '($5) ? ($6) : ($7)';
do {
$str = preg_replace($pattern, $replacement, $str, -1, $count);
} while ($count);
echo $str;
preferences:
27.66 ms | 404 KiB | 5 Q