2010-03-08 109 views
1

我想按字母后跟的規則拆分文本。所以我這樣做:如何按字母順序拆分?

$text = 'One two. Three test. And yet another one'; 
$splitted_text = preg_split("/\w\./", $text); 
print_r($splitted_text); 

然後我得到這個:

Array ([0] => One tw [1] => Three tes [2] => And yet another one) 

但我確實需要它是這樣的:

Array ([0] => One two [1] => Three test [2] => And yet another one) 

如何解決這個問題?

回答

2

使用explode語句中使用

$text = 'One two. Three test. And yet another one'; 
$splitted_text = explode(".", $text); 
print_r($splitted_text); 

更新

$splitted_text = explode(". ", $text); 

「」 在explode聲明還檢查了空間。

你可以使用任何類型的分隔符也是一個短語非只有一個字符

+0

可能想在這種情況下使分隔符「。」來擺脫空間,但是是的。這個。 – badideas

1

使用正則表達式是矯枉過正這裏,你可以很容易地使用explode。由於爆炸基於答案已經給出,我給一個基於正則表達式的答案:

$splitted_text = preg_split("/\.\s*/", $text); 

正則表達式中使用:\.\s*

  • \. - 一個點是元字符。爲了匹配文字匹配,我們逃避它。
  • \s* - 零個或多個空白區域。

如果使用正則表達式:\.

你有一些前導空格在一些創建的作品。

2

它在信件和期間分裂。如果您想測試以確保在期間之前有一封信,則需要在斷言後面使用積極的看法。

$text = 'One two. Three test. And yet another one'; 
$splitted_text = preg_split("/(?<=\w)\./", $text); 
print_r($splitted_text);