简体   繁体   中英

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. 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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