5

我想用一系列单词分割一个大字符串。

例如

$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 的文件。

4

4 回答 4

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);
于 2011-11-10T03:19:21.950 回答
5

preg_split可以用作:

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

看见

于 2011-11-10T03:22:14.360 回答
4

我认为没有必要使用 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."
}

与您的输出的唯一区别是最后一个单词,因为“单词”。!= "word" 并且它不是一个拆分词。

于 2011-11-10T03:42:44.893 回答
-1

由于 $splitby 数组中的单词不是正则表达式,也许您可​​以使用

str_split

于 2011-11-10T03:18:48.270 回答