-1

私は次のような文字列を持っています:

Quaint village location, seaside views, four bedrooms

次のことを行う必要があります。

  • コンマで区切られた各項目を取り、それを配列に追加します
  • 先頭と末尾の空白を削除
  • 最初の文字を大文字にする

たとえば、上記の文字列は次のようになります。

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

trimを使用してこのコード ブロックを開始しましたが、あまり効率的な方法ではないexplodeucfirst思います。

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 つのタスクを実行する最も効率的な方法は何ですか?

4

2 に答える 2

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',
)

デモ

于 2015-10-13T10:01:43.143 に答える
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");
于 2015-10-13T10:03:39.353 に答える