PHP preg_split:按其他字符串拆分字符串
我想用一系列单词来拆分一个大字符串 例如 那么结果将是:PHP preg_split:按其他字符串拆分字符串,php,regex,preg-split,Php,Regex,Preg Split,我想用一系列单词来拆分一个大字符串 例如 那么结果将是: $text[0]='This is'; $text[1]='string which needs'; $text[2]='be'; $text[3]='above'; $text[4]='.'; 我该怎么做?是最好的方法,还是有更有效的方法?我希望它尽可能快,因为我将拆分数百MB的文件。由于$splitby数组中的单词不是正则表达式,您可以使用 这应该是合理有效的。但是,您可能希望使用一些文件进行测试,并报告性能 $splitby =
$text[0]='This is';
$text[1]='string which needs';
$text[2]='be';
$text[3]='above';
$text[4]='.';
我该怎么做?是最好的方法,还是有更有效的方法?我希望它尽可能快,因为我将拆分数百MB的文件。由于$splitby数组中的单词不是正则表达式,您可以使用
这应该是合理有效的。但是,您可能希望使用一些文件进行测试,并报告性能
$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);
- 正则表达式演示:
- PHP代码演示:
preg\u split
可以用作:
$pieces = preg_split('/'.implode('\s*|\s*',$splitby).'/',$text,-1,PREG_SPLIT_NO_EMPTY);
我认为没有必要使用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”并且它不是拆分的单词。
str\u split()
不能用字符串分隔字符串。它只是将一个字符串拆分为一个字符数组,长度等于最后一个参数的长度(默认值为1)。考虑到他想按特定的单词拆分字符串,而不是将其拆分为单词大小的块,这个答案没有意义。这正是我想要的。谢谢大家!@阿拉斯代尔:很高兴能帮忙!注意codaddict
关于\s*
的建议,如果示例数据中的单词之间可能有一个以上的空格,这可能会很有用。感谢您的帮助。虽然in_array()对于大型数组非常慢,但preg_split要快得多。也许你是对的,但如果你使用preg_split,你可能会得到“编译失败:正则表达式在偏移量*******处太大”。我只是尝试了5490个单词的数组,结果失败了。结果是preg_split花了我太长时间。请参阅下面我的解决方案。您的解决方案很好,但in_array()函数在PHP中存在问题。检查数组中某个值是否存在的一种更快的方法是数组翻转数组,然后使用isset()检查键是否存在,这比在数组中使用大约快1000倍。数组翻转+isset似乎是个好主意。但对于一个200k元素的数组来说,差别“只有”30ms。根据我的经验,差别是秒与小时,字面上来说。我认为in_array()存在严重问题。无论如何,无论是preg_拆分还是我发布然后删除的方法都没有达到我想要的效果。我现在正在测试您修改为使用isset()的方法。注意:如果在$splitby上执行array\u flip,然后使用isset()而不是在\u array()中,racar的答案是最快的。preg_split不起作用,因为$splitby中有数百个单词。
$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."
}