将“xxx-yyyy people”形式的数据拆分为两个变量php

时间:2012-03-25 15:32:02

标签: php

鉴于我在格式中有一个变量$ peopleSize(我已经从UI元素中提取了信息):

xxx-yyyy people

例如,如jquery范围UI中所示:

http://jsfiddle.net/methuselah/SLvtx/1/

如何使用PHP摆脱“ - ”和“人”,将两个min和max作为两个单独的变量?

4 个答案:

答案 0 :(得分:5)

一种简单的方法是使用sscanf()之类的

sscanf("3-456 people", "%d-%d", $min, $max);
// $min contains 3, $max contains 456

答案 1 :(得分:2)

执行此操作的方法之一:'-'' '上的split the string

$peopleSize = 'xxx-yyyy people';
$parts = preg_split('-| ', $peopleSize);
$min = $parts[0];
$max = $parts[1];

答案 2 :(得分:2)

list($min, $max) = explode('-', strtok($peopleSize, ' '));

答案 3 :(得分:1)

<?php
$str = "300-1000 people";

preg_match("|(\d+)-(\d+)|", $str, $matches);

//$matches[0] will hold the whole min-max string.

$min = $matches[1]; //First matched group, first set of numbers.
$max = $matches[2]; //Second matched group, second set of numbers.

echo "$min to $max";