如何剥离简单的句子,剥离第三个句号?

时间:2015-02-27 15:32:16

标签: php

我有一长串文字,如何限制输出以计算完整停止数,只输出说到第三个完整停止?

Ex Raw:

  

Lorem Ipsum只是印刷和排版行业的虚拟文本。自16世纪以来,Lorem Ipsum一直是业界标准的虚拟文本,当时一台未知的打印机采用了类型的厨房,并将其拼凑成一本类型的样本。它不仅存在了五个世纪,而且还延续了电子排版,基本保持不变。它不仅存在了五个世纪,而且还延续了电子排版,基本保持不变。

所需输出

  

Lorem Ipsum只是印刷和排版行业的虚拟文本。自16世纪以来,Lorem Ipsum一直是业界标准的虚拟文本,当时一台未知的打印机采用了类型的厨房,并将其拼凑成一本类型的样本书。

 // Long text
 $profile_desc = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.';

 // Split long text on each full stop.
 $profile_desc_out = explode( '. ', $profile_desc );

 $i = 0;
 // Repeat 3 times to get three sentences 
 foreach( $profile_desc_out as $profile_desc_output ){
   echo $profile_desc_output;
   if( ++$i > 3 ) {
     break;
   }
 }
 // How to incorporate implode() function to put back together? 

1 个答案:

答案 0 :(得分:0)

与往常一样,RegExp来救援:)

3是要显示的最大句子数。 1是最低计数。

// Long text
$profile_desc = "This paragraph. Has. More. Than three. Sentences.";

preg_match('#^(?:[^\.]+\.){1,3}#', $profile_desc, $matches);
echo $matches[0], PHP_EOL;

输出:

This paragraph. Has. More.