简体   繁体   中英

Parse String Array of regex values within PHP

The combination of the way I'm working with this is complex and I can't find any reference on how to accomplish it.

I'm allowing the user to store a representation of an array of regex values in the database (MySql) like so:

'["/^\d{5}([\-]?\d{4})?$/i", "/^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/i"]'

Now in my PHP code I read it into a variable $val and it looks like this:

'["/^\\d{5}([\\-]?\\d{4})?$/i", "/^([ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJKLMNPRSTVWXYZ])\\ {0,1}(\\d[ABCEGHJKLMNPRSTVWXYZ]\\d)$/i"]'

and trying to leverage JSON to decode it into an actual array:

$val = '{"unq":'.$val.'}';
$obs = json_decode($val);
return $obs->unq;

Problem is, I get Notice: Trying to get property of non-object in... on $obs->unq;

I'm guessing this has to do with the way the regex is being stored, but I'm not certain. Too many wasted hours on this, thanks for your help.

It seem's your parser (mysqli_real_escaped_string or something else) does not escape any of structural characters expected in a json string (except unicode chars i guess)

As you can read in the JSON RFC about strings escaping slashes (forward or backward) should be escaped !

"The representation of strings is similar to conventions used in the C family of programming languages"

Then, you can use addcslashes to escape it:

$reg = addcslashes($reg, chr(0x5c)); // hex notation, beware of '\\'
$out = '{"unq":'.$reg.'}';
$out = json_decode($out);

Hint

You should use native debug functions like var_dump and json error handler to ensure where error occur from:

var_dump(json_last_error_msg(), $out);
return $out->unq;

in error way:

string(12) "Syntax error"
NULL

solved:

string(8) "No error"
object(stdClass)#1 (1) {
  ["unq"]=>
  array(2) {
    [0]=>
    string(23) "/^\d{5}([\-]?\d{4})?$/i"
    [1]=>
    string(86) "/^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/i"
  }
}

Storage

I dont know about your purpose, but there is another way to help on this king of storage. You can also serialize a true array of regex

// before saving
$patterns = serialize
([
    "/^\d{5}([\-]?\d{4})?$/i",
    "/^([ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ])\ {0,1}(\d[ABCEGHJKLMNPRSTVWXYZ]\d)$/i",
]);

// usage out of mysql, unserialize do the tricks
return $patterns = unserialize($sqlressource["patterns"]);

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