我想将此字符串拆分为3个数组元素。
MW 01:00 PM-02:30 PM
输出:
array[0] = MW
array[1] = 01:00 PM
array[2] = 02:30 PM
用正则表达式帮助我,该表达式会将字符串提取到数组中。
^[a-zA-Z\d-_]+$
答案 0 :(得分:4)
答案 1 :(得分:1)
<?php
$str = "MW 01:00 PM - 02:30 PM";
$matches = [];
preg_match("/^([a-zA-Z]+)\s+(\d{1,2}:\d{1,2}\s+PM)\s+\-\s+(\d{1,2}:\d{1,2}\s+PM)$/",$str,$matches);
print_r($matches);
输出
Array
(
[0] => MW 01:00 PM - 02:30 PM
[1] => MW
[2] => 01:00 PM
[3] => 02:30 PM
)
答案 2 :(得分:1)
这也可以(但更长):
$str = "MW 01:00 PM - 02:30 PM";
preg_match('/([A-Z]{2}) ([0-9]{2}:[0-9]{2} [A-Z]{2}) - ([0-9]{2}:[0-9]{2} [A-Z]{2})/', $str, $match);
echo '<pre>' . print_r($match, true) . '</pre>';
输出:
Array
(
[0] => MW 01:00 PM - 02:30 PM
[1] => MW
[2] => 01:00 PM
[3] => 02:30 PM
)