2

PHP を使用して、番号付きリストを含む文字列から配列を抽出しようとしています。

文字列の例:

The main points are: 1. This is point one. 2. This is point two. 3. This is point three.

次の配列になります。

[0] => 1. This is point one.
[1] => 2. This is point two.
[2] => 3. This is point three.

文字列の形式はさまざまです。例:

1. This is point one, 2. This is point two, 3. This is point three.
1) This is point one  2) This is point two 3) This is point three
1 This is point one. 2 This is point two. 3 This is point three.

次のパターンでpreg_match_allの使用を開始しました。

!((\d+)(\s+)?(\.?)(\)?)(-?)(\s+?)(\w+))!

しかし、残りの文字列/次の一致までを一致させる方法がわかりません。

RegExrで利用可能な例

4

2 に答える 2

4

各「ポイント」に数値自体が含まれていないため、入力が入力例に従う場合は、次の正規表現を使用できます。

\d+[^\d]*

preg_match_all()PHP では、すべてをキャプチャするために使用できます。

$text = 'The main points are: 1. This is point one. 2. This is point two. 3. This is point three.';

$matches = array();
preg_match_all('/(\d+[^\d]*)/', $text, $matches);

print_r($matches[1]);

これにより、次のようになります。

Array
(
    [0] => 1. This is point one.
    [1] => 2. This is point two.
    [2] => 3. This is point three.
)

繰り返しますが、実際のポイント自体に数字/数字がある場合、これは機能しません。

各ポイントに実際の数値を表示する場合は、ピリオドなど、各ポイントの実際の「アンカー」または「終了」を定義する必要があります。a がポイントの最後にのみ表示されることを述べることができる場合.(先頭の桁に続く可能性のあるものは無視します)、次の正規表現を使用できます。

\d+[.)\s][^.]*\.

preg_match_all()上から に簡単にドロップできます。

preg_match_all('/(\d+[.)\s][^.]*\.)/', $text, $matches);

正規表現は次のように説明しました。

\d+        # leading number
[.)\s]     # followed by a `.`, `)`, or whitespace
[^.]*      # any non-`.` character(s)
\.         # ending `.`

2 番目の正規表現の注意点は、a.が各ポイントの末尾 (および先頭の数字の後に) にのみ表示される可能性があることです。ただし、このルールは「ポイントに数字がない」ルールよりも従うのが簡単かもしれないと思います-それはすべてあなたの実際の入力に依存します.

于 2012-11-06T06:00:28.830 に答える
0

preg_splitを使用すると簡単です。番号付け形式に基づいて文字列を分割し、空でない結果を返すだけです。ニーズに合わせてこれを変更します。

http://codepad.org/tK6fGCRB

<?php

$theReg = '/\d\.|\d\)|\d /';
$theStrs = array(
                '1. This is point one, 2. This is point two, 3. This is point3' ,
                '1) This is point one  2) This is point two 3) This is point 3' ,
                '1 This is point one. 3 This is point three. 4 This is point 4'
                );

foreach($theStrs as $str)
   print_r(preg_split($theReg, $str , -1 , PREG_SPLIT_NO_EMPTY));;
?>
于 2012-11-06T06:03:23.460 に答える