Php 字符串操作(提取第一个单词)


Php Strings manipulations (Extract first word)

我在下面有一段话,我想从中得到一个句号的每个结尾的第一个词。

$paragraph="Microsoft is writing down $6.2 billion of the goodwill within its OSD. It's worth noting that at the time of the acquisition, the company recorded $5.3 billion of goodwill assigned to the OSD, bringing its total carrying balance up to $5.9 billion in September of that year. The goodwill in the OSD had climbed up to $6.4 billion by March of this year, so this accounting charge is wiping out the vast majority of that figure.";

例如,我可以这样做。

$sentences=explode('.',$paragraph);
print_r( $sentences);

它打印

Array ( [0] => Microsoft is writing down $6
        [1] => 2 billion of the goodwill within its OSD 
        [2] => It's worth noting that at the time of the acquisition, the company recorded $5 
        [3] => 3 billion of goodwill assigned to the OSD, bringing its total carrying balance up to $5                            
        [4] => 9 billion in September of that year 
        [5] => The goodwill in the OSD had climbed up to $6 
        [6] => 4 billion by March of this year, so this accounting charge is wiping out the vast majority    of that figure 
        [7] => )

但是,我在徘徊,如何从每个数组中获取第一个单词。例如,如何创建一个将获得第一个单词的函数,如下例所示:

微英尺2它39这四

谢谢

在每个句子上使用explode(),但使用空格而不是句点。

$paragraph = "Microsoft is writing down $6.2 billion of the goodwill within its OSD. It's worth noting that at the time of the acquisition, the company recorded $5.3 billion of goodwill assigned to the OSD, bringing its total carrying balance up to $5.9 billion in September of that year. The goodwill in the OSD had climbed up to $6.4 billion by March of this year, so this accounting charge is wiping out the vast majority of that figure.";
$sentences = explode('.', $paragraph);
foreach($sentences as $sentence){
 $words = explode(' ', trim($sentence));
 $first = $words[0];
 echo $first;
}
$paragraph="Microsoft is writing down $6.2 billion of the goodwill within its OSD. It's worth noting that at the time of the acquisition, the company recorded $5.3 billion of goodwill assigned to the OSD, bringing its total carrying balance up to $5.9 billion in September of that year. The goodwill in the OSD had climbed up to $6.4 billion by March of this year, so this accounting charge is wiping out the vast majority of that figure.";
firstWords($paragraph);
function firstWords($paragraph) {
  $sentences = explode('.', $paragraph);
  foreach ($sentences as $sentence) {
   $words = explode(' ', trim($sentence));
   echo $words[0];
  }
}