我有一个像这样的字符串:
Quaint village location, seaside views, four bedrooms
我需要做以下事情:
例如,上面的字符串变为:
array(
[0] => 'Quaint village location',
[1] => 'Seaside views',
[2] => 'Four bedrooms',
)
我已使用trim
,explode
和ucfirst
启动此代码块,但我认为我不会以非常有效的方式进行此操作。
iif(get_field('property_information') != NULL){
$raw_facilities_list = explode(",", get_field('property_information'));
$other_facilities_list = [];
foreach($raw_facilities_list as $facility){
$facility = trim($facility);
$facility = ucfirst($facility);
array_push($other_facilities_list,$facility);
}
$property['extra_features'] = $other_facilities_list;
echo '<pre>';
var_dump($property);
echo '</pre>';
}
执行这3项任务的最有效方法是什么?
答案 0 :(得分:2)
只需使用array_map
和explode
$property['extra_features'] = array_map(function($v){
return ucfirst(trim($v));
},explode(',',$str));
<强>输出:强>
array(
[0] => 'Quaint village location',
[1] => 'Seaside views',
[2] => 'Four bedrooms',
)
答案 1 :(得分:0)
你做得对;但是你可以把它分成几部分:
function sanitize($string){
return ucfirst(trim($string));
}
function treat($sentence)
{
return join(",",(array_map('sanitize',explode(",",$sentence))));
}
$array[] = treat("Quaint village location, seaside views, four bedrooms");