使用 preg-match 推送到 Foreach 中的多维数组



我在使用 preg_match 构造多维数组时遇到了一些困难。

我试图将一个段落分解成句子。然后对于段落的每个部分/句子,我想将每个单词和标点符号分解到数组的另一个级别。

@Toto昨天帮助我进行了预配,以爆炸字符串,同时保留标点符号作为元素。

但是,我一直在努力构建我想要的数组。

考虑这样的段落:

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的内容,但现在我对数组复制每个部分并将它们添加到数组 [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);

你快到了,我只是添加了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] => .
        )
)

最新更新