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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

Thanks -.-

 

I wonder why that didn't come up when I was searching for an existing solution, checked the php text functions to see if it was there (url_decode etc are, so was expecting this one to be there as well).

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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