我在$ a中有一个时隙数组:
10:00 am,11:00 am,12:00 pm,01:00 pm,02:00 pm,03:00 pm,04:00 pm
我想从数组中删除除am/pm
的第一个实例以外的所有实例:
10:00 am,11:00,12:00 pm,01:00 pm,02:00,03:00, 04:00
str_replace()
会全力以赴。 preg_replace
会让我限制我取出的数量,但不会让我除外1.但是我需要为此编写自己的功能吗?是否有优雅的解决方案?
答案 0 :(得分:0)
你可以试试这个,它只保留你想要的第一个上午/下午字符串:
select STUFF((Select ','+email_receiver from dbo.rms_emails where is_active =1 FOR XML PATH('')),1,1,'')
输出:
$timeSlots = array(
"10:00 am",
"11:00 am",
"12:00 pm",
"01:00 pm",
"02:00 pm",
"03:00 pm",
"04:00 pm"
);
$foundAm = false;
$foundPm = false;
foreach( $timeSlots as $index => $timeSlot ) {
if( strpos( $timeSlot, "am" ) !== false && $foundAm === false ) {
$foundAm = true;
continue;
} else if( strpos( $timeSlot, "pm" ) !== false && $foundPm === false ) {
$foundPm = true;
continue;
}
$timeSlots[$index] = trim( str_replace( array( "am", "pm" ) , "", $timeSlot ) );
}
echo "<pre>";
var_dump( $timeSlots );
echo implode( ",", $timeSlots );
答案 1 :(得分:0)
如果它的类似这样的数组可以工作,我想(只有当没有设置键或者你知道第一个键时)
$times = array('10:00 am','11:00 am','12:00 pm','01:00 pm','02:00 pm','03:00 pm','04:00 pm');
foreach($times as $key => $time){
if($key != 0){
$search = array(" am", " pm");
$times[$key] = str_replace($search, "", $time);
}
//So if the key is 0 (The first element) continue, else remove the am/pm
}