2010-03-08 71 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);