How would I select two numbers from a string, using preg_match
?
I've used preg_match
before to select only <iframe>
and a #
tag.
For example I need to select the two numbers in an equation:
$message = 'whats 23x347?';
And give me an output variable as such:
$first_number = 23
$seccond_number = 347
list($first_number, $second_number) = preg_split("/x/",$message);
This mostly works, however it does not remove the non-numeric text before nor after.
you could do it in two ways. preg_split would be easiest but preg_match also works, it's just a little more work.
preg_split
$equation = "23x347";
list($first_number, $second_number) = preg_split("/x/",$equation);
print_r(array('first_number' => $first_number, 'second_number' => $second_number));
preg_split would return the two values as separate list elements.
Array
(
[first_number] => 23
[second_number] => 347
)
preg_match
$equation = "23x347?";
list($first_number, $second_number) = preg_match("/(\d+)x(\d+).*/",$equation);
print_r($matches);
preg_match would populate the $matches array
Array
(
[0] => 3x347?
[1] => 23
[2] => 347
)