It is possible to extract from an input string an array of strings composed only integers independent of specifying some separator.
For this just split the input string to each character that is not a decimal digit with preg_match_all
.
The function preg_match_all()
captures the matches of a pattern regular expression in a string.
One can instruct the preg_match_all()
that captures only the integer numbers of the string with the pattern
/[-+]?\d+/
.
The flag PREG_SET_ORDER
sorts the results so that the first value of the capture matrix is the first matching set, the second value of the capture matrix is the matching set and so on.
With the function array_map()
apply the conversion function to integers intval()
each element of the array previously returned by preg_match_all()
flattened by the function array_merge()
.
With list()
assign an array to multiple variables.
<?php
$entrada = readline("Informe o primeiro e o segundo número inteiro: ");
preg_match_all('/[-+]?\d+/', $entrada, $numeros, PREG_SET_ORDER);
list($numero1, $numero2) = array_map('intval', array_merge(...$numeros));
var_dump($numero1);
var_dump($numero2);
Test the example on Repl.it
The person will separate by space, comma or what? If you can [Dit] and give an example of what the input is, it helps. I’m trying to locate other posts that talk about it, but basically that’s it, you do it
$linha = readline('texto');
without the int, will come a stirng. There does$valores = explode('separador',$linha);
, then the values will be in$primeiro = (int) $valores[0]
,$segundo = (int) $valores[1]
... etc.– Bacco