从PHP中的字符串返回多个整数

从PHP中的字符串返回多个整数

问题描述:

I am trying to return the numbers from a string as separate integers. The string has the following markup:

$string = "20 x 20 cm";

The number 20 could be a larger number as well. e.g. 70 x 93 cm or 120 x 230 cm, so it isn't always equal to each other.

I've read about Preg_Match, but couldn't figure it out. So now I'm here asking for your help.

Thanks in advance!

我试图将字符串中的数字作为单独的整数返回。 该字符串具有以下标记: p>

  $ string =“20 x 20 cm”; 
  code>  pre> 
 
 

数字 20也可能是更大的数字。 例如 70 x 93厘米或120 x 230厘米,所以它并不总是彼此相等。 p>

我读过Preg_Match,但无法弄明白。 所以现在我在这里寻求你的帮助。 p>

提前致谢! p> div>

You could use

$string = '20 x 20 cm';
$arr = explode(' ', $string);
$arr = array($arr[0], $arr[2]);
print_r($arr);

I'm not a regex master, but I like to work with named subpatterns:

$string = "20 x 20 cm";
preg_match('/(?P<int1>\d+) x (?P<int2>\d+)/', $string, $matches);
echo $matches['int1'].', '.$matches['int2'];

Another option would be strtok:

$int1 = strtok($string, ' x ');
$int2 = strtok(' x ');
echo $int1.', '.$int2;

Or use sscanf:

list($int1, $int2) = sscanf($string, "%d x %d cm");
echo $int1.', '.$int2;

This should work for you

$string = "20 x 20 cm";
$results = array();
preg_match_all('/\d+/', $string, $results);
print_r($results[0]);