简体   繁体   English

我应该如何划分一串正则表达式?

[英]How should I delimit a string of regular expressions?

I want to store a few regular expressions in a text field in a mysql database. 我想在mysql数据库的文本字段中存储一些正则表达式。 Currently my best idea is to use an irregular pattern of symbols for my delimiter. 目前我最好的想法是为我的分隔符使用不规则的符号模式。 Example: 例:

$delim = '!@#$%';
$regex1 = '/^(.+)$/';
$regex2 = '/.(.+)./';
$regex3 = '/(\s+):\/\//';
$string = $regex1.$delim.$regex2.$delim.$regex3;

$string would then be stored in the database. 然后$ string将存储在数据库中。 To retrieve I'd use something like: 要检索我会使用类似的东西:

$array = explode($delim,$string);

What I'd like to know is if there's a better, more accurate method than just hoping my delimiter doesn't appear in one of the regexs. 我想知道的是,如果有一种更好,更准确的方法,而不仅仅是希望我的分隔符不出现在其中一个正则表达式中。

Yep, much better way. 是的,更好的方式。 Use serialize() or json_encode() when putting them in the database and unserialize() or json_decode() when pulling them out. 将它们放入数据库时​​使用serialize()json_encode() ,并在将它们拉出时使用unserialize()json_decode()

This has the benefit of not failing in a catastrophic way which ends up taking you forever to debug. 这样做的好处是不会以灾难性的方式失败,最终会让你永远地进行调试。

<?php
$string = json_encode( array( $regex1, $regex2, $regex3 ) );

// Later
$array = json_decode( $string );

为什么不使用空字节, \\0

One of the reasons we use databases, is so we won't have to come up with delimiters ourselves, but instead we can just let the database handle how the data is stored. 我们使用数据库的原因之一是,我们不必自己提出分隔符,而是让数据库处理数据的存储方式。

Now, you're inventing your own data structure, even though your database can do it all by itself. 现在,您正在创建自己的数据结构,即使您的数据库可以单独完成所有操作。

What I'm trying to say is: You should store each part of the regex in its own row and let your DBMS worry about the rest. 我想说的是:你应该将正则表达式的每个部分存储在自己的行中,让你的DBMS担心其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM