Jump to content

Converting a string into a regular expression


Axeia

Recommended Posts

My head hurts from writing this thing:

private function convert2regex( $pStr )
{
    return preg_replace( '~(\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\))~', '\\\$0', $pStr );
}

But that oughta do the job, right? Took all the characters with a special meaning , escaped them, used the or operator and captured the result to a backreference.

Then the backreference is prefixed with a backslash and the preg_replace puts in the proper spot.

My head hurts from writing this thing:

private function convert2regex( $pStr )
{
    return preg_replace( '~(\[|\\|\^|\$|\.|\||\?|\*|\+|\(|\))~', '\\\$0', $pStr );
}

But that oughta do the job, right?

 

Well, without an example string of what you are trying to capture, it's hard to say..

 

Alternations can be costly.. I would advise a character class instead of all these ORs...

return preg_replace( '~([\[^$.|?*+()\\\])~', '\\\$0', $pStr );// hope I didn't miss any characters

 

Perhaps seeing a complete string example before and with the desirable after effects would help illuminate what it is you are trying to accomplish if the above snippet doesn't serve well...

Trying to convert basically ANY string into a regular expression.

So anything that has a special meaning in a regular expression has to be escaped.

 

Or that was the plan earlier today, using it atm for something a bit less random and so far so good.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.