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."
}

出力との唯一の違いは、「単語」であるため、最後の単語です。!= "単語" であり、分割単語ではありません。

于 2011-11-10T03:42:44.893 に答える
-1

$splitby 配列の単語は正規表現ではないため、使用できる可能性があります

str_split

于 2011-11-10T03:18:48.270 に答える