我需要把一段分成几个句子。这就是我有点搞不懂的地方。
我已经引用了这个Q标记为副本的question。但这里的问题是不同的。
这里是我需要拆分的字符串的一个示例:
你好!你好吗?生活怎么样? 过生活,过自由。“不是吗?”
这里是我尝试过的代码:
$sentence_array = preg_split('/([.!?\r\n|\r|\n])+(?![^"]*")/', $paragraph, -1);我需要的是:
array (
[0] => "hello"
[1] => "how are you"
[2] => "how is life"
[3] => "live life, live free"
[4] => ""isnt it?""
)我得到的是:
array(
[0] => "hello! how are you? how is life live life, live free. "isnt it?""
)当字符串中没有引号时,拆分将按需要工作。
任何帮助都是非常感谢的。谢谢。
发布于 2018-09-28 08:45:45
正则表达式中存在一些问题,主要是将组结构与字符类混淆。字符类中的管道|实际上是指|。它没有什么特别的意义。
你需要的是:
("[^"]*")|[!?.]+\s*|\R+这首先尝试匹配以双引号括起来的字符串(并捕获内容)。然后尝试匹配[!?.]设置的标点符号以在其上拆分。如果找到任何类型的换行符,都可以使用。
PHP:
var_dump(preg_split('~("[^"]*")|[!?.]+\s*|\R+~', <<<STR
hello! how are you? how is life
live life, live free. "isnt it?"
STR
, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));输出:
array(5) {
[0]=>
string(5) "hello"
[1]=>
string(11) "how are you"
[2]=>
string(11) "how is life"
[3]=>
string(20) "live life, live free"
[4]=>
string(10) ""isnt it?""
}发布于 2018-09-28 08:16:30
我认为您基于某些标点符号拆分的问题已经解决了,只是在双引号的情况下失败了。我们可以用一个解决方案来表达,当我们看到这样的标点符号时,或者当看到这个标点符号后面跟着双引号时,我们应该分开。
当前面的字符与你的一个标记匹配,下面不是双引号,或者前两个字符应该是一个标记和一个双引号时,就会发生分裂。这意味着按照以下模式进行拆分,该模式使用查找器:
(?<=[.!?\r\n])(?=[^"])|(?<=[.!?\r\n]")(?=.)代码示例:
$input = "hello! how \"are\" \"you?\" how is life\nlive life, live free. \"isnt it?\"";
$sentence_array = preg_split('/(?<=[.!?\r\n])(?=[^"])|(?<=[.!?\r\n]\")(?=.)/', $input, -1);
print_r($sentence_array);
Array ( [0] => hello! [1] => how "are" "you?" [2] => how is life
[3] => live life, live free. [4] => "isnt it?" )https://stackoverflow.com/questions/52551031
复制相似问题