The file receives the values ​​"1 0 1 -1 -3 1 1 1 1" and the value "154". The php code counts all the digits:

$file = file_get_contents('test.txt'); preg_match_all("/[^\b\d{4}\/\d{2}\/\d{2}\b][0-9\.-]+/", $file, $numbers); foreach($numbers[0] as $num) { $sum = $sum + $num; //складываем } $data = $sum 

Is it possible to make so that "154" was not considered together with other figures, but was a separate variable? You can enclose a number in any specials. characters and brackets if that helps.

  • 2
    It seems to me alone that delirium is written in regular expression? - Visman
  • one
    If you have numbers in the string, separated by spaces, then convert the string to an array by spaces, then convert the array elements in the loop from strings to numbers and do with it what you want. - Visman
  • I am sure that regular expressions do not even need to try to solve this problem. The problem is solved by splitting the string into spaces and simple comparisons. - tutankhamun
  • publish the test.txt file - Mi Ke Bu
  • Let test.txt be = "1 0 1 -1 -3 1 1 1 1 154" - Alex Spiridonov

1 answer 1

If the contents of the file = "1 0 1 -1 -3 1 1 1 1 154", then the following regular expression will do:

 /(?:\b154\b)|(-?\d+)/g 

It searches for 154 , цифры , -цифры , but 154 does not remember

Link to the example: https://regex101.com/r/iG1uT2/2