note 125521 added to regexp.reference.recursive
| From: | mzvarik at gmail dot com | Date: | Wed, 18 Nov 2020 10:53:58 +0000 |
| Subject: | note 125521 added to regexp.reference.recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-215862@lists.php.net to get a copy of this message | ||
This regexp can be used for parsing IF conditions.
$str = '
(IF_MYVAR)My var is printed
(OR_MYVARTWO)My var two is printed
(OR_ANOTHER)if you use OR you don't have to END everytime
(ELSE)Whatever bro(END)
(IF_BLUE)Something (IF_SUPERB)super(END) blue - this is simple IF condition(END)
';
function isCondition($k) {
// put your user conditions here
$conds = [];
$conds['BLUE'] = true;
$conds['MYVARTWO'] = true;
$conds['ELSE'] = true; // always true
return $conds[$k];
}
function findConditions($str) {
$pattern = '~ \(if_([^\)]+)\) ((?: (?!\((end|if_)). | (?R) )*+) \(end\) ~xis';
$str = preg_replace_callback($pattern, function($m) {
$k = $m[1];
$v = $m[2];
$v = findConditions($v) ?: $v;
$ors = preg_split('~(?=\((OR_[^\)]+|ELSE))~is', $v);
$v = array_shift($ors); // hlavnÃ
if (isCondition($k)) return findConditions($v);
else {
foreach ($ors as $or) {
list($k, $v) = explode(")", $or, 2);
$k = substr($k, 1);
if (isCondition($k)) return findConditions($v);
}
}
return ''; // no matching condition
}, $str);
return $str;
};
// will output: Whatever bro \n\n Something blue
echo findConditions($str);
----
Server IP: 45.112.84.4
Probable Submitter: 185.85.3.174 (proxied: 85.135.47.154)
----
Manual Page -- http://php.net/manual/en/regexp.reference.recursive.php
Edit -- https://master.php.net/note/edit/125521
Del: integrated -- https://master.php.net/note/delete/125521/integrated
Del: useless -- https://master.php.net/note/delete/125521/useless
Del: bad code -- https://master.php.net/note/delete/125521/bad+code
Del: spam -- https://master.php.net/note/delete/125521/spam
Del: non-english -- https://master.php.net/note/delete/125521/non-english
Del: in docs -- https://master.php.net/note/delete/125521/in+docs
Del: other reasons-- https://master.php.net/note/delete/125521
Reject -- https://master.php.net/note/reject/125521
Search -- https://master.php.net/manage/user-notes.php