1

次のような形式のテキスト ブロックを解析する必要があります。

Today the weather is excellent bla bla bla.
<temperature>35</temperature>. 
I'm in a great mood today. 
<item>Desk</item>

このようなテキストを解析し、次のような配列に変換したい:

$array[0]['text'] = 'Today the weather is excellent bla bla bla. ';
$array[0]['type'] = 'normalText';

$array[1]['text'] = '35';
$array[1]['type'] = 'temperature';

$array[2]['text'] = ". I'm in a great mood today.";
$array[2]['type'] = 'normalText';

$array[3]['text'] = 'Desk';
$array[3]['type'] = 'item';

基本的に、配列には元のテキストと同じ順序ですべてのテキストを含めたいのですが、タイプに分割します: 通常のテキスト (タグの間にないものを意味します)、および温度、アイテムなどの他のタイプ。テキストが間にあるタグによって決定されました。

これを行う方法はありますか (つまり、正規表現を使用してテキストを通常のテキストと他のタイプに分離します)、または舞台裏でテキストを適切に構造化されたテキストに変換する必要があります。

<normal>Today the weather is excellent bla bla bla.</normal>
<temperature>35</temperature>.
<normal> I'm in a great mood today.</normal><item>Desk</item>

テキストを解析しようとする前に?

4

2 に答える 2

3

編集:期待どおりに動作するようになりました!

解決:

<?php

$code = <<<'CODE'
Today the weather is excellent bla bla bla.
<temperature>35</temperature>. 
I'm in a great mood today. 
<item>Desk</item>
CODE;

$result = array_filter(
    array_map(
        function ($element) {
            if (!empty($element)) {
                if (preg_match('/^\<([^\>]+)\>([^\<]+)\</', $element, $matches)) {
                    return array('text' => $matches[2],
                                 'type'    => $matches[1]);
                } else {
                    return array('text' => $element,
                                 'type'    => 'normal');
                }
            }
            return false;
        },
        preg_split('/(\<[^\>]+\>[^\<]+\<\/[^\>]+\>)/', $code, null, PREG_SPLIT_DELIM_CAPTURE)
    )
);

print_r($result);

出力:

Array
(
    [0] => Array
        (
            [text] => Today the weather is excellent bla bla bla.

            [type] => normal
        )

    [1] => Array
        (
            [text] => 35
            [type] => temperature
        )

    [2] => Array
        (
            [text] => . 
I'm in a great mood today. 

            [type] => normal
        )

    [3] => Array
        (
            [text] => Desk
            [type] => item
        )

)
于 2012-10-19T07:17:02.533 に答える
1

テキストを 1 行ずつ読んでみてください。2 つのケースがあります。通常のテキストを追加し、特別なタグを持つテキストを追加します。通常のテキストを変数に追加する際に、regexp を含むタグを探します。

preg_match("/\<(\w)\>/", $line_from_text, $matches) 

() は、配列で使用する単語を $matches に保存します。終了タグに到達するまで、変数にテキストを追加するだけです。お役に立てれば。

于 2012-10-19T05:36:13.857 に答える