3v4l.org

run code in 300+ PHP versions simultaneously
<?php function parse($pattern) { $matches = ''; $variables = array(); $pos = 0; $reg = '#'; //It seems that regex must start and end with a delimiter $nextText = ''; if($pattern == '/') { $reg = '#^[\/]+$#'; return ['variables' => '', 'regex' => $reg]; } //Check if generated regexes are stored, if so it skips the whole process /*if(apc_exists($pattern)) { $cacheI = apc_fetch($pattern); return $cacheI; }*/ //Extracts the variables enclosed in {} preg_match_all('#\{\w+\}#', $pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER); //Puts each variable in array //Uses the text before and after to create a regex for the rest of the pattern - $precedingText, $nextText //If no wildcard is detected in the path it splits it into segments and compiles are regex foreach ($matches as $match) { $varName = substr($match[0][0], 1, -1); $precedingText = substr($pattern, $pos, $match[0][1] - $pos); $pos = $match[0][1] + strlen($match[0][0]); $nxt = $pos - strlen($pattern); if($nxt == 0) $nxt = strlen($pattern); $nextText = substr($pattern, $nxt); $precSegments = explode('/', $precedingText); $precSegments = array_splice($precSegments, 1); //Pulls a regex from the preeceding segment, each variable segment is replaced with '\/[a-zA-Z0-9]+' if(strlen($precedingText) > 1) { foreach($precSegments as $key => $value) { $reg .= '\/'; $reg .= $value; } $reg .= '[a-zA-Z0-9]+'; } else { $reg .= '\/[a-zA-Z0-9]+'; } $nextText = str_replace('/', '\/', $nextText); if(is_numeric($varName)) { throw new \Exception('Argument cannot be a number'); } if (in_array($varName, $variables)) { throw new \Exception(sprintf('More then one occurrence of variable name "%s".', $varName)); } $variables[] = $varName; } //If no variable names, wildcards are found in pattern : /hello/static/path it will replace it with \/hello\/static\/path if(count($matches) < 1 && $pattern != '/') { $reg .= str_replace('/', '\/', $pattern); } $reg = $reg . $nextText; $reg .= '#'; //apc_store($pattern, ['variables' => $variables, 'regex' => $reg]); return ['variables' => $variables, 'regex' => $reg]; } $data = parse('hi/{p1}/cicki/{p2}'); echo 'parse: '.var_export($data, 1);
Output for git.master, git.master_jit, rfc.property-hooks
parse: array ( 'variables' => array ( 0 => 'p1', 1 => 'p2', ), 'regex' => '#\\/[a-zA-Z0-9]+\\/cicki\\/[a-zA-Z0-9]+#', )

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
98.29 ms | 405 KiB | 5 Q