2011-11-10 88 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