如果我错了,请纠正我,但我认为你不能用一个简单的正则表达式来做到这一点。在一个完整的正则表达式实现中,你可以使用这样的东西:
$parts = preg_split("/(?<!<[^>]*)\./", $input);
但是 php 不允许非固定长度的lookbehind,所以这是行不通的。显然,仅有的两个是 jgsoft 和 .net 正则表达式。 Useful Page
我的处理方法是:
function splitStringUp($input, $maxlen) {
$parts = explode(".", $input);
$i = 0;
while ($i < count($parts)) {
if (preg_match("/<[^>]*$/", $parts[$i])) {
array_splice($parts, $i, 2, $parts[$i] . "." . $parts[$i+1]);
} else {
if ($i < (count($parts) - 1) && strlen($parts[$i] . "." . $parts[$i+1]) < $maxlen) {
array_splice($parts, $i, 2, $parts[$i] . "." . $parts[$i+1]);
} else {
$i++;
}
}
}
return $parts;
}
当单个句子的长度超过 8000 个字符时,您没有提及您想要发生的事情,所以这只是让它们保持原样。
样本输出:
splitStringUp("this is a sentence. this is another sentence. this is an html <a href=\"a.b.c\">tag. and the closing tag</a>. hooray", 8000);
array(1) {
[0]=> string(114) "this is a sentence. this is another sentence. this is an html <a href="a.b.c">tag. and the closing tag</a>. hooray"
}
splitStringUp("this is a sentence. this is another sentence. this is an html <a href=\"a.b.c\">tag. and the closing tag</a>. hooray", 80);
array(2) {
[0]=> string(81) "this is a sentence. this is another sentence. this is an html <a href="a.b.c">tag"
[1]=> string(32) " and the closing tag</a>. hooray"
}
splitStringUp("this is a sentence. this is another sentence. this is an html <a href=\"a.b.c\">tag. and the closing tag</a>. hooray", 40);
array(4) {
[0]=> string(18) "this is a sentence"
[1]=> string(25) " this is another sentence"
[2]=> string(36) " this is an html <a href="a.b.c">tag"
[3]=> string(32) " and the closing tag</a>. hooray"
}
splitStringUp("this is a sentence. this is another sentence. this is an html <a href=\"a.b.c\">tag. and the closing tag</a>. hooray", 0);
array(5) {
[0]=> string(18) "this is a sentence"
[1]=> string(25) " this is another sentence"
[2]=> string(36) " this is an html <a href="a.b.c">tag"
[3]=> string(24) " and the closing tag</a>"
[4]=> string(7) " hooray"
}