I do not understand why he does not want to save the result in the group?

Here is the regular expression

(?:(\d+)-?)+ /// То есть он ловит примерное следущее 53453-3234-324234-24324-5234 

I need the result to be saved in groups:

 1. 53453 2. 3234 3. 324234 4. 24324 5. 5234 

But for some reason, now he is not saving in groups as it should, at the moment he is saving only one group and this is the last one, that is 5234 . I would also like not to save the dash to the groups that I actually showed above.

  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin

3 answers 3

Such spaces in PHP have to be solved in 2 steps:

  • Split the text into (isolate) the desired groups (here you can use (\d+):{(\d+(?:-\d+)*)} ).
  • You can explode("-", $m[2]) texts captured by group 2 (you can use explode("-", $m[2]) , in more difficult cases, you can use the second preg_match(_all) ).

Everything can be done in preg_replace_callback to get the desired result in 1 pass.

Sample PHP code :

 $s = "4:{227-130-191},8:{97},9:{98},14:{99},15:{195-160}"; $ar = array(); preg_replace_callback('/(\d+):{(\d+(?:-\d+)*)}/', function($m) use (&$ar) { $ar[$m[1]] = explode("-", $m[2]); }, $s); print_r($ar); 
  • well, even though this is not exactly what I expected, but it is very close to what you need - MaximPro
  • In .NET, you could do everything according to you, there is a CaptureCollection , in Python, PyPi regex there are captures , but there is no such thing in PHP. - Wiktor Stribiżew
  • understandable, well, this option also comes down, it is not bulky yet - MaximPro

if you want to skip everything except numbers, it will do:

  (?:(\d+))+ 

php code

  <?php $re = '/(?:(\d+))+/'; $str = '53453-3234-324234-24324-5234'; preg_match_all($re, $str, $matches); // Print the entire match result print_r($matches); 
  • No, this is not what you need - MaximPro
  • then, nevertheless, in 2 stages and using explode ^ _ ^ through the regular season $re = '/(([\d\-]+))/'; you receive all groups with - , and further through explode you break, on the necessary arrays. - myxaxa
  • it was found out earlier, explode I don’t like it, just using it alone doesn’t give the flexibility that regulars give - MaximPro

The code will be something like this:

 $numbersString = '53453-3234-324234-24324-5234'; $arrayOfNumbers = explode('-', $numbersString); print_r($arrayOfNumbers); 

Result:

 Array ( [0] => 53453 [1] => 3234 [2] => 324234 [3] => 24324 [4] => 5234 ) 
  • Well, are you kidding me? I asked to use explode? - MaximPro