Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GimmeMylanta's avatar

Saving regex expressions to DB

Hey Guys,

I was wondering if someone could guide me on the best way to store regex expressions to the DB, and retrieving them.

I'm trying to write a catalog of different nasty code strings, but im finding it quite difficult.

For instance, one expression is

<\?php[\x00-\x1f\s]if\(\!isset\(\$GLOBALS\[\"\\x

When I insert it into the DB using the standard Model::firstOrCreate and then try to extract it, it prints is as follows;

<\\?php[\\x00-\\x1f\\s]if\\(\\!isset\\(\\$GLOBALS\\[\\\"\\\\x

Any help would be greatly appreciated.

0 likes
12 replies
Sinnbeck's avatar

Does it look right if you run it through stripcslashes after getting it from the db?

$data = stripcslashes($data);
GimmeMylanta's avatar

I get the following;

Malformed UTF-8 characters, possibly incorrectly encoded"

GimmeMylanta's avatar

Im still getting the same error :( ... Should I be doing something on the insert command?

gitwithravish's avatar

It is weird, I myself passed your encoded string to utf8_decode and it showed expected output. What data type are you using for the regex string column by the way?

gitwithravish's avatar

Manually encode the string before inserting to database and decode like the following while retrival.

//encode while inserting
Model::create([
	'col' => addslashes($string)
	...
])

//decode while retrieving 
$data = stripslashes($model->col)


GimmeMylanta's avatar

That addslashes and stripslashes didn't work, It just gave me the same output that I had in my question

gitwithravish's avatar

What solution are you exactly looking for? When you insert an expression in database, it encodes the result and you want to decode it while retrieving right?

GimmeMylanta's avatar

Im trying to build a catalog of bad expressions used in coding.

Would it work if i base64 encoded it on insert and decode on extraction?

Sinnbeck's avatar

If you dont need to be able to read it in the database directly, you could try base64 encoding it (you can add mutators and accessors to make this process automatic)

//encode while inserting
Model::create([
	'col' => base64_encode($string)
	...
])

//decode while retrieving 
$data = base64_decode($model->col)
1 like
Sinnbeck's avatar
public function getRegexAttribute($value)
{
    return base64_decode($value);
}

public function setRegexAttribute($value)
{
    $this->attributes['regex'] =  base64_encode($value);
}
2 likes

Please or to participate in this conversation.