我想用PHP preg_split
內置函數將字符串分割成數組。PHP preg_split:用連字符分割字符串
例如:
我有這個字符串:51-200 employees
和我想要的結果是沒有employees
字符串:
array (
0 => '51',
1 => '200',
)
我想用PHP preg_split
內置函數將字符串分割成數組。PHP preg_split:用連字符分割字符串
例如:
我有這個字符串:51-200 employees
和我想要的結果是沒有employees
字符串:
array (
0 => '51',
1 => '200',
)
如果你只有一個斜槓後面無用字符分隔的兩個整數,你可以使用一個格式化字符串sscanf
:
$result = sscanf('51-200 employees', '%d-%d');
簡單又甜美。奇蹟般有效。 TQ。 –
如果字符串總是格式'<number>-<number2> employees'
可以使explode()
使用:
$string = '51-200 employees';
$splittedString = explode(' ', $string);
$numbers = explode('-', $splittedString[0]);
將輸出array([0] => 51, [1] => 200)
。
php preg_split()
按分隔符分隔字符串,但您希望從字符串中選擇數字。使用preg_match_all()
更好。
$str = "51-200 employees";
preg_match_all("/\d+/", $str, $matches);
var_dump($matches[0]);
參見導致demo
您是否嘗試過爆炸? http://php.net/manual/en/function.explode.php –
@ka_lin是的,我試過了,結果是數組(0 =>'51',1 =>'200 employees')預計一個是數組0 =>'51',1 =>'200') –
使用'preg_match_all(「/ \ d + /」,$ str,$ matches)' – Mohammad