使用preg_match构建多维数组时遇到一些困难。
我试图将一个段落分成句子。 然后对于段落的每个部分/句子,我想将每个单词和标点符号分解为数组的另一个级别。
@Toto昨天帮助我使用preg-match来爆炸字符串,同时保留标点符号作为元素。
但是,我一直在努力构建我想要的数组。
考虑一个这样的段落:
First section. This section, and this. How about this section? And a section; split in two.
作为回报,结果如下:
Array ( [0] =>
Array ( [0] => First [1] => section [2] => . )
Array ( [1] =>
Array ( [0] => This [1] => section [2] => , [3] => and [4] => this [2] => . )
Array ( [2] =>
Array ( [0] => How [1] => about [2] => this [3] => section [4] => ? )
Array ( [3] =>
Array ( [0] => And [1] => a [2] => section [3] => ; [4] => split
[5] => in [6] => two [7] => . )
)))
它不起作用。我不太确定在构建第二个维度后如何删除$ s的内容但是现在我更加困惑的是数组复制每个部分并将它们添加到Array [0] ??
$m = ' First section. This section, and this. How about this section? And a section; split in two.'
$s = preg_split('/\s*[!?.]\s*/u', $m, -1, PREG_SPLIT_NO_EMPTY);
foreach ($s as $x => $var) {
preg_match_all('/(\w+|[.;?!,:]+)/', $var, $a);
array_push($s, $a);
}
print_r($s);
答案 0 :(得分:1)
你差不多了,我刚刚添加PREG_SPLIT_DELIM_CAPTURE
并更改了preg_split
的正则表达式。所以你可以这样使用:
$str = 'First section. This section, and this. How about this section? And a section; split in two.';
$matchDelim = preg_split("/([^.?!]+[.?!]+)/", $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$finalArr = [];
foreach ($matchDelim as $match) {
preg_match_all('/(\w+|[.;?!,:])/', $match, $matches);
$finalArr[] = $matches[0];
}
print_r($finalArr);
结果:
Array
(
[0] => Array
(
[0] => First
[1] => section
[2] => .
)
[1] => Array
(
[0] => This
[1] => section
[2] => ,
[3] => and
[4] => this
[5] => .
)
[2] => Array
(
[0] => How
[1] => about
[2] => this
[3] => section
[4] => ?
)
[3] => Array
(
[0] => And
[1] => a
[2] => section
[3] => ;
[4] => split
[5] => in
[6] => two
[7] => .
)
)