2011-11-10 86 views
4

我想通過一系列字詞拆分大字符串。PHP preg_split:將字符串拆分爲其他字符串

例如

$splitby = array('these','are','the','words','to','split','by'); 
$text = 'This is the string which needs to be split by the above words.'; 

那麼結果將是:

$text[0]='This is'; 
$text[1]='string which needs'; 
$text[2]='be'; 
$text[3]='above'; 
$text[4]='.'; 

我怎樣才能做到這一點?是preg_split最好的方法,還是有更高效的方法?我希望它儘可能快,因爲我將分割數百MB的文件。

+0

Afternote:racar的答案是最快的,如果array_flip在$ splitby上執行,然後使用isset()而不是in_array()。 preg_split不起作用,因爲$ splitby中有數百個單詞。 – Alasdair

回答

3

我不認爲使用pcre正則表達式是必要的......如果它真的分裂你需要的話。

你可以做這樣的事情和指標看它的速度更快/更...

$splitby = array('these','are','the','words','to','split','by'); 
$text = 'This is the string which needs to be split by the above words.'; 

$split = explode(' ', $text); 
$result = array(); 
$temp = array(); 

foreach ($split as $s) { 

    if (in_array($s, $splitby)) { 
     if (sizeof($temp) > 0) { 
      $result[] = implode(' ', $temp); 
      $temp = array(); 
     }    
    } else { 
     $temp[] = $s; 
    } 
} 

if (sizeof($temp) > 0) { 
    $result[] = implode(' ', $temp); 
} 

var_dump($result); 

/* output 

array(4) { 
    [0]=> 
    string(7) "This is" 
    [1]=> 
    string(18) "string which needs" 
    [2]=> 
    string(2) "be" 
    [3]=> 
    string(5) "above words." 
} 

與輸出唯一的區別是因爲硬道理「的話。」 !=「單詞」,它不是一個分詞。

+0

謝謝你的幫助。雖然in_array()對於大數組非常緩慢,但preg_split要快得多。 – Alasdair

+0

也許你是對的,但是如果你使用preg_split,你可能會得到「編譯失敗:正則表達式在offset ******上太大」。我試着用5490個單詞來嘗試,但失敗了。 – malletjo

+0

事實證明,preg_split時間太長了我的喜好。請參閱下面的解決方案你的解決方案很好,但in_array()函數在PHP中有問題。檢查數組中某個值存在的更快方法是array_flip數組,然後使用isset()檢查密鑰是否存在,比使用in_array()快大約1000倍。 – Alasdair

-1

由於在$ splitby陣列的話不是正則表達式也許你可以使用

​​

+0

'str_split()'不能用字符串分隔字符串。它只是將一個字符串分割成最後一個參數長度的字符數組(默認爲1)。 –

+0

這個答案沒有意義,考慮到他想按特定單詞分割字符串,而不是將其分割成單詞大小的塊。 –

7

這應該是相當有效的。但是,您可能想要測試一些文件並報告性能。

$splitby = array('these','are','the','words','to','split','by'); 
$text = 'This is the string which needs to be split by the above words.'; 
$pattern = '/\s?'.implode($splitby, '\s?|\s?').'\s?/'; 
$result = preg_split($pattern, $text, -1, PREG_SPLIT_NO_EMPTY); 
+0

正是我想要的。謝謝! – Alasdair

+0

@Alasdair:很高興幫助!注意'\ s *'的'codaddict'建議,如果您的示例數據中的單詞之間可能存在多個空格,這可能很有用。 – mellamokb

4

preg_split可作爲:

$pieces = preg_split('/'.implode('\s*|\s*',$splitby).'/',$text,-1,PREG_SPLIT_NO_EMPTY); 

See it