1

私は有用性/硬さのために正規表現を好き/嫌いです。(理由はわかりませんが、パターンを作成できません:()
データベースフィールドに次のようなレコードがいくつかあります

[(ip1=192.x.?.100)(id1=125485smds65)(date1=11.02.2011-15:00/15.06.2012-17:30)(text1=Some text that can include all brackets and/or parentheses & any chars etc, like < ( text . } , [ any ) ] { etc.**)][(ip2=x.x.20.?)(num2=1235845)(text2=many other words :))]...

わかりました。次のような値を含む配列を返したいと思います。

$result[ip1] = 192.x.?.100;
$result[id1] = 125485smds65;
$result[date1] = 11.02.2011-15:00/15.06.2012-17:30;
$result[text1] = Some text that can include all brackets and/or parentheses & any chars etc, like < ( text . } , [ any ) ] { etc.**;
$result[ip2] = 192.x.?.100;
$result[num2] = 1235845;
$result[text2] = many other words :)

かっこ内のデータ数とかっこ数が異なる場合があることがわかります

では、preg_match_all正規表現が上記のデータを収集するための真のパターンは何ですか?

4

2 に答える 2

4

次のようなものを試してください。

$s = '(ip1=192.x.?.100)(id1=125485smds65)(date1=11.02.2011-15:00/15.06.2012-17:30)
(text1=Some text that can include all brackets and/or paranthesis & any chars etc, 
like < ( text . } , [ any ) ] { etc.**)][(ip2=x.x.20.?)(num2=1235845)
(text2=many other words :))';

preg_match_all('/\((?:[^()]|(?R))*\)/', $s, $matches);

print_r($matches);

印刷されます:

Array
(
    [0] => Array
        (
            [0] => (ip1=192.x.?.100)
            [1] => (id1=125485smds65)
            [2] => (date1=11.02.2011-15:00/15.06.2012-17:30)
            [3] => (text1=Some text that can include all brackets and/or paranthesis & any chars etc, 
like < ( text . } , [ any ) ] { etc.**)
            [4] => (ip2=x.x.20.?)
            [5] => (num2=1235845)
            [6] => (text2=many other words :)
        )

)

(?R)正規表現パターンの/\((?:[^()]|(?R))*\)/は、パターン全体への再帰的な呼び出しです。

質問の下のコメントから明らかなように、本番コードでこのような正規表現を使用することはお勧めしません。私の提案は、データベースのようにデータを保存しないことです。根本的に問題を解決してください!

于 2011-11-10T22:12:21.430 に答える
0

あなたができること:

/(\(([^)=]*)=([^)]*)\))*/

ただし、これは不可能です。「すべての角かっこや括弧を含めることができる一部のテキスト」-世界で、テキストを閉じ括弧とどのように区別しますか?

そして、これが非常に貧弱なデータ構造である場合に備えて。まず第一に、それはデータベースです-それは列を持っています、それらを使用してください!次に、なぜ独自のデータ構造をローリングするのですか?jsonまたはphpを使用できますserialize()

正規表現は、このジョブには不適切なツールです。

于 2011-11-10T22:12:17.310 に答える