I have variables of form like:$x = "1-15"
$y = "2-18"
etc.
I need to extract the first and second integer as separate variables.
For example:
if $x = "1-15"
, return values should be $z = 1
and $w = 15
.
I know that It would be possible to do this with regex, but from what I've heard, it should be avoided if possible.
What then would be the "fastest" way of achieving this?
If you are sure this is the format, you can split the string (assuming it is a string, and not literally what you wrote).
Splitting is done with explode
in php: http://php.net/manual/en/function.explode.php
$x = "1-15"; //assuming it is indeed a string
list($z, $w) = explode('-', $x);
Using explode
is a better option, If you want to go with regex
, Hope this solution will be okay.
Regex: ^\s*(\d+)\s*\-\s*(\d+)\s*$
1.
^\s*(\d+)\s*\-\s*(\d+)\s*$
This will matchdigits - digits
pattern, this will take care of spaces as well.
<?php
$x = '1-15';
extract(getVariables($x));
echo $z;
echo $w;
function getVariables($x)
{
preg_match("/^\s*(\d+)\s*\-\s*(\d+)\s*$/", $x,$matches);
return array("z"=>$matches[1],"w"=>$matches[2]);
}