Php preg_match_all, check and explode

I want to check 'n' to blow this line:

{$gallery#pager/collectionName/imageName/manual/no_effect/foo1/foo2/.../fooN} 

in

 var_name[0] => 'gallery', modul_name[0] => 'pager', 3[0] => 'collectionName', 4[0] => 'imageName', 5[0] => 'manual' ... N[0] => 'fooN' 

I did the following regexp:

 /{\$(?P<var_name>[^#]+)#(?P<module_name>[^\/]+)(?:\/(\w+)(?:\/(\w+)(?:\/(\w+)(?:\/(\w+)(?:\/(\w+))?)?)?)?)?}/ 

but it is too ugly and only supports up to five parameters. Please help me make the recursive part to extract all the parameters.

ps: Yes, I can split it into var_name , computer_name and parameters , then I can explode part by '/' parameters , but I don't like it.

+5
source share
2 answers

You can use preg_split() .

Regex:

 preg_split('@([$#])|[{}/] +@ ', $text) 

And discard the first and third elements of the array.

ideone demo



EDIT: To reflect the new conditions set by OP in the comments (not in the question): it should check the syntax ^\{\$\w+#\w+(?:/\w*)$ and tokenize in var, module and parameters independently.

Regex:

 ~\G(?(?=^)\{\$(\w++)#(\w++)(?=[\w/]+}$))/\K\w*+~ 

Code:

 // http://stackoverflow.com/q/32969465/5290909 $pattern = '@\G(?(?=^)\{\$(\w++)#(\w++)(?=[\w/]+}$))/\K\w* +@ '; $text = '{$gallery#pager/collectionName/imageName/manual/no_effect/foo1/foo2/fooN}'; $result = preg_match_all($pattern, $text, $matches); if ($result === 0) { // is invalid, does not match '~^\{\$\w+#\w+(?:/\w*)+$~' echo "Invalid text"; } else { // Assign vars (only to clarify) $module_name = array_pop($matches)[0]; $var_name = array_pop($matches)[0]; $parameters = $matches; echo "VAR NAME: \t'$var_name'\nMODULE: \t'$module_name'\nPARAMETERS:\n"; print_r($matches); } 

Output:

 VAR NAME: 'gallery' MODULE: 'pager' PARAMETERS: Array ( [0] => collectionName [1] => imageName [2] => manual [3] => no_effect [4] => foo1 [5] => foo2 [6] => fooN ) 

ideone demo

+3
source
 {\$([^#]+)#|\G(?!^)([^\/]+)\/|\G(?!^)(.*?)}$ 

You can just make a match and grab a demonstration of groups .See.

https://regex101.com/r/cJ6zQ3/18

 $re = "/{\\$([^#]+)#|\\G(?!^)([^\\/]+)\\/|\\G(?!^)(.*?)}$/m"; $str = "{\$gallery#pager/collectionName/imageName/manual/no_effect/foo1/foo2/.../fooN}"; preg_match_all($re, $str, $matches); 
+2
source

Source: https://habr.com/ru/post/1233044/


All Articles