最有效的解决方案:通过逗号对字符串进行修剪,大写和爆炸

时间:2015-10-13 09:59:22

标签: php string trim ucfirst

我有一个像这样的字符串:

Quaint village location, seaside views, four bedrooms

我需要做以下事情:

  • 将每个逗号分隔的项目添加到数组中
  • 从开头和结尾删除空格
  • 将第一个字母大写

例如,上面的字符串变为:

array(
   [0] => 'Quaint village location',
   [1] => 'Seaside views',
   [2] => 'Four bedrooms',
)

我已使用trimexplodeucfirst启动此代码块,但我认为我不会以非常有效的方式进行此操作。

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项任务的最有效方法是什么?

2 个答案:

答案 0 :(得分:2)

只需使用array_mapexplode

即可
$property['extra_features'] = array_map(function($v){
  return ucfirst(trim($v));
},explode(',',$str));

<强>输出:

array(
   [0] => 'Quaint village location',
   [1] => 'Seaside views',
   [2] => 'Four bedrooms',
)

Demo

答案 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");