2011-06-22 72 views
5

我做一個句子拆分字爲如下:
如:我如何拆分字符串文字和符號的組合陣列

This is a test from php, python, asp and also from other languages. Alash! i cannot get my output as followings. 

結果:

array( 
[0]=>"This", 
[1]=>"is", 
[2]=>"a", 
[3]=>"test", 
[4]=>"from", 
[5]=>"php", 
[6]=>",", 
[7]=>"python", 
[8]=>",", 
[9]=>"asp", 
[10]=>"and", 
[11]=>"also", 
[12]=>"from", 
[13]=>"other", 
[14]=>"languages", 
[15]=>".", 
[16]=>"Alash", 
[17]=>"!", 
[18]=>"I", 
[19]=>"cannot", 
[20]=>"get", 
... 
) 

什麼可以成爲我的選擇在PHP中呢?

回答

2

嘗試類似:

preg_split('/\s+|\b/', $string) 
+0

這東西GR8 ......會喜歡跳過空格太 – KoolKabin

+1

更好地使用'/ \ s +試試這個方法| \ B(?= \ W)/',然後你不要結束所有那些空的字符串。 – mhyfritz

+0

gr8 one ... thnx它的工作 – KoolKabin

1

你可以嘗試像

$res = preg_split('/ |([.,])/' , $string,-1, PREG_SPLIT_DELIM_CAPTURE| PREG_SPLIT_NO_EMPTY); 
+0

對不起,它沒有按預期工作.... – KoolKabin

+0

你嘗試編輯的? – Shameer

2

哇財產以後,這是一個艱難的!因爲你還想保留「,」。這裏是做什麼:

$string = "I beg to differ, you can get it as the previous."; 
$words = preg_split('/\s+|(?<=[,\.!\?])|(?=[,\.!\?])/',$string); 

注:在(?<=)並在(?=),你必須把所有要被視爲字爲好,即使之前沒有空格字符和/或在他們之後。

+1

這應該是一個正確的答案。 – sznowicki

2

使用爆炸

function multiexplode ($delimiters,$string) 
{ 

    $ready = str_replace($delimiters, $delimiters[0], $string); 
    $launch = explode($delimiters[0], $ready); 
    return $launch; 
} 

$text = "here is a sample: this text, and this will be exploded. this also | this one too :)"; 

$exploded = multiexplode(array(",",".","|",":"),$text); 

print_r($exploded);